Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery selector syntax for value of innerText

I'm trying to add a click event to a tab that's generated by a Telerik ASP.NET widget. I've lifted a snip of the generated HTML into a static page for the purposes of experimentation:

<HTML>
<HEAD>
<TITLE>sandpit</TITLE>
<SCRIPT TYPE="text/javascript" SRC="jquery-1.9.1.js"></SCRIPT>
<SCRIPT>
$(document).ready(function(){
  var foo = $("span.rtsTxt");
  var bar = foo.filter("[innerText='More']")
  bar.on('click',function(){alert('click');});
  alert('ready');
});
</SCRIPT>
</HEAD>
<BODY>
  <ul>
    <li class="rtsLI">
      <a class="rtsLink rtsAfter">
        <span class="rtsOut">
          <span class="rtsIn">
            <span class="rtsTxt">Preferences</span>
          </span>
        </span>
      </a>
    </li>
    <li class="rtsLI">
      <a class="rtsLink rtsAfter">
        <span class="rtsOut">
          <span class="rtsIn">
            <span class="rtsTxt">More</span>
          </span>
        </span>
      </a>
    </li>
  </ul>
</BODY>
</HTML>

Debugging reveals that foo contains two items as expected. However, I can't figure out the syntax for selected the second one where the value of innerText is "More".

The question is simply how do I express innerText == 'More' either in a filter expression as shown or directly in the selector string?

like image 741
Peter Wone Avatar asked Mar 21 '13 03:03

Peter Wone


2 Answers

One more approach to select an element which will return an object is to use filter like this:

$(".rtsTxt").filter(function() {
    return $(this).text() == "More";
});   

fiddle

like image 159
RAS Avatar answered Sep 21 '22 17:09

RAS


Try the :contains selector:

var bar = foo.filter(":contains('More')")

Here's a jsfiddle demo showing it working.

WARNING: Although this will work for the html in the question, the :contains selector will match any element that contains the given text, not just the element whose text equals the given text. (As @RAS pointed out in a comment below.)

like image 41
John S Avatar answered Sep 17 '22 17:09

John S