Mr. Jo
Mr. Jo

Reputation: 5251

Check if ul has li with a specific text in jQuery

I'm currently trying to check, if there is a li element in my ul which has a specific text. When I enter this here in the console, I'm receiving all li texts:

jQuery(".et-pb-contact-message.contact-error ul:nth-child(2)").has("li").text();
"Name *E-Mail-Adresse *Betreff *Nachricht *Bestätigung"

Now I've wrote this statement into an if block, but it's sadly not working:

if (!jQuery(".et-pb-contact-message.contact-error ul:nth-child(2)").has("li").text() === 'Captcha *') {
    alert("No captcha error");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="et-pb-contact-message contact-error">
  <p>Bitte fülle die folgenden Felder aus:</p>
  <ul>
    <li>Name&nbsp;*</li>
    <li>E-Mail-Adresse&nbsp;*</li>
    <li>Betreff&nbsp;*</li>
    <li>Nachricht&nbsp;*</li>
    <li>Bestätigung</li>
  </ul><ul></ul>
</div>

Upvotes: 0

Views: 854

Answers (4)

Shiva Kumar Potti
Shiva Kumar Potti

Reputation: 11

jQuery(".et-pb-contact-message.contact-error ul:nth-child(2) li").each(function(){
  console.log(this.innerText);
});

Use this code to check each and every value.

Upvotes: 1

barzin.A
barzin.A

Reputation: 1582

jQuery(".contact-error ul:nth-child(2) li").each(function(index) {
  if ($(this).html() === 'Captcha&nbsp;*')
    console.log('founded in ' + (index + 1) + 'th error');
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="et-pb-contact-message contact-error">
  <p>Bitte fülle die folgenden Felder aus:</p>
  <ul>
    <li>Name&nbsp;*</li>
    <li>Captcha&nbsp;*</li>
    <li>Betreff&nbsp;*</li>
    <li>Nachricht&nbsp;*</li>
    <li>Bestätigung</li>
  </ul>
  <ul></ul>
</div>

Upvotes: 1

Grudin Maksim
Grudin Maksim

Reputation: 86

if (!(jQuery(".et-pb-contact-message.contact-error ul:nth-child(2)").has("li").text()).split(" ").includes('Captcha *')) {
    console.log("enjoy!");
  }

But keep in mind that the includes method does not work in ie.

Upvotes: 1

shrys
shrys

Reputation: 5940

var flag = false;
jQuery(".et-pb-contact-message.contact-error ul:nth-child(2) li").each((idx, ele) => {
  console.log(ele.innerText);
  if (!flag && ele.innerText == 'Captcha *') {
    flag = true;
  }
});
if (!flag)
  alert("No captcha error");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="et-pb-contact-message contact-error">
  <p>Bitte fülle die folgenden Felder aus:</p>
  <ul>
    <li>Name&nbsp;*</li>
    <li>E-Mail-Adresse&nbsp;*</li>
    <li>Betreff&nbsp;*</li>
    <li>Nachricht&nbsp;*</li>
    <li>Bestätigung</li>
    <!--<li>Captcha&nbsp;*</li>-->
  </ul>
  <ul></ul>
</div>

Upvotes: 2

Related Questions