Jin Yong
Jin Yong

Reputation: 43778

Check span attribute contains text in Jquery

Just wandering, will it be possible to check span attribute contains text in Jquery?

Example: I have the following html code:

<div id="test">
    <div class="user-name">
     <span class="user_title">Mrs Support</span>
     <span class="org_name" org-full-name="Test">Moon Company</span>
     <span><a class="mutual">3 mutual user</a></span></div>
</div>

I want to find out attribute org-full-name value contains "es" .

I tried the following code, but it's not working

$("#test").find(".user-name:icontains('es')")

Upvotes: 0

Views: 104

Answers (3)

Omar Einea
Omar Einea

Reputation: 2524

You could simply do it like this:

$("#test .org_name").attr("org-full-name").indexOf("es") > 0

This will return true if "es" is contained inside the attribute's value or false otherwise.

Upvotes: 0

charlietfl
charlietfl

Reputation: 171669

Use filter(). A :contains selector only works on text, not on attribute values

$("#test .user-name [org-full-name]").filter(function(){
   return $(this).attr('org-full-name').toLowerCase().indexOf('es')>-1
}).css('color','red')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">
  <div class="user-name">
    <span class="user_title">Mrs Support</span>
    <span class="org_name" org-full-name="Test">Moon Company</span>
    <span><a class="mutual">3 mutual user</a></span>
  </div>
    <div class="user-name">
    <span class="user_title">Uncle Support</span>
    <span class="org_name" org-full-name="Foo">Howl at Moon</span>
    <span><a class="mutual">9 mutual user</a></span>
  </div>
      <div class="user-name">
    <span class="user_title">Support Junior</span>
    <span class="org_name" org-full-name="Especially">Unemployed</span>
    <span><a class="mutual">9 mutual user</a></span>
  </div>
</div>

Upvotes: 1

Tushar Gupta
Tushar Gupta

Reputation: 15923

It is an alternative approach, but you can use .indexOf.It will return true or False based on the text

console.log($("#test span[org-full-name=Test]").text().indexOf("es")>=0)


//alternate way to have the text based approach
console.log($("#test span[org-full-name]").text().indexOf("es")>=0)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test">
    <div class="user-name">
     <span class="user_title">Mrs Support</span>
     <span class="org_name" org-full-name="Test">Test</span>
     <span><a class="mutual">3 mutual user</a></span></div>
</div>

Upvotes: 1

Related Questions