0

I have a few divs with comma separated values in each. If the word 'public' is present in the values, I want to display the word 'Yes'. Else, I want to display the word 'No'. I am using if else and indexOf. Should I be using.each(function () instead?

<div class="open-public">ses, public</div>
<div class="open-public">public, der</div>
<div class="open-public">public</div>
<div class="open-public">fder, stn</div>
<div class="open-public">public</div>
<div class="open-public">stn</div>


    var s = $(".open-public").text().trim();
    var match = s.split(', ')
    console.log(match)
    console.log(s)
 
 if (~match.indexOf("public")) {
      $('.open-public').text("Yes");
    } else {
      $('.open-public').text('No');
}

I have also tried this:

    $(".open-public").each(function () {
    if ($(this).is(':contains("public")').text("Yes");
    } else {
        $('.open-public').text('No');
    }
});

fiddle here

1
  • I tried it here but I think I am missing something. new fiddle Commented Jul 8, 2021 at 23:40

1 Answer 1

1

Your .each approach is the correct one but you really don't need jQuery for this.

For matching the text, I would recommend either splitting the CSV text value into an array or using a regex to match the entire word "public".

const rx = /\bpublic\b/ // use word-boundaries to match the entire word
document.querySelectorAll(".open-public").forEach(el => {
  el.textContent = rx.test(el.textContent) ? "Yes" : "No"
})
<div class="open-public">ses, public</div>
<div class="open-public">public, der</div>
<div class="open-public">public</div>
<div class="open-public">fder, stn</div>
<div class="open-public">public</div>
<div class="open-public">stn</div>


If you're set on using jQuery, it might look something like this

const rx = /\bpublic\b/
$(".open-public").each(function() {
  const $this = $(this)
  $this.text(rx.test($this.text()) ? "Yes" : "No")
})
Sign up to request clarification or add additional context in comments.

1 Comment

This works great. thank you. newest fiddle

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.