John Brad
John Brad

Reputation: 467

JQuery check if <li> contains specific text

I am trying to check if anchor contains specific text but unfortunately it did not work for me.

I have text like this: REGISTER | LOG IN |SIGN OUT

I have written JavaScript code below.

var logintxt = $(".login-info2 a").text();
if ($('.login-info2 a:contains("Sign Out")').length > 0) {  
    console.log(logintxt + " yes");
}

HTML Code is below.

<li class="user-info2">
    <a class="smalltext" href="/register">Register</a>&nbsp;|&nbsp;
    <a class="smalltext" href="/login">Log&nbsp;In</a>
</li>

<li class="user-info2">
    <a class="smalltext" href="/signout">Sign&nbsp;Out</a>
</li>

Unfortunately it is not working. Can any tell how to resolve this issue?

Thanks

Upvotes: 0

Views: 791

Answers (4)

connexo
connexo

Reputation: 56770

Since you have HTML entities in your link texts, it is probably more reliable to check the link target instead:

if ([...linklist.querySelectorAll('a')].some(a => a.getAttribute('href') === '/signout')) {
  console.log('logout link found');
} else {
  console.log('none found')
};
<ul id="linklist">
  <li class="user-info2">
    <a class="smalltext" href="/register">Register</a>&nbsp;|&nbsp;
    <a class="smalltext" href="/login">Log&nbsp;In</a>
  </li>

  <li class="user-info2">
    <a class="smalltext" href="/signout">Sign&nbsp;Out</a>
  </li>
</ul>

Or with jQuery:

if ($('#linklist a[href="/signout"]').length) {
  console.log('logout link found');
} else {
  console.log('none found')
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="linklist">
  <li class="user-info2">
    <a class="smalltext" href="/register">Register</a>&nbsp;|&nbsp;
    <a class="smalltext" href="/login">Log&nbsp;In</a>
  </li>

  <li class="user-info2">
    <a class="smalltext" href="/signout">Sign&nbsp;Out</a>
  </li>
</ul>

Upvotes: 1

Gurdeep Singh
Gurdeep Singh

Reputation: 41

var logintxt = $(".login-info2").text();

if ($('.login-info2:contains("Sign Out")').length > 0) {  
    console.log(logintxt + " yes");
}

This way works for me check it

Upvotes: 3

Syed mohamed aladeen
Syed mohamed aladeen

Reputation: 6755

Try like this.

$(".user-info2 a").each(function(){
   var logintxt = $(this).html().replace(/&nbsp;/g, ' ').toLowerCase();
  if (logintxt == "sign out") {
      console.log(logintxt + " yes");
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<li class="user-info2">
    <a class="smalltext" href="/register">Register</a>&nbsp;|&nbsp;
    <a class="smalltext" href="/login">Log&nbsp;In</a>
</li>

<li class="user-info2">
    <a class="smalltext" href="/signout">Sign&nbsp;Out</a>
</li>

Upvotes: 2

Ajay Kumar
Ajay Kumar

Reputation: 97

You can use it like:

var logintxt = $(".login-info2 a").text();
if(logintxt.toLowerCase() === "sign up"){
 console.log(logintxt + " Yes");
}

Upvotes: 1

Related Questions