Wednesday 3 February 2010

Select elements by innerHTML with jQuery

Sometimes it is necessary to use jQuery to select html elements with a certain innerHTML value.  Consider the following 3 labels:

<label>apples</label>
<label>oranges</label>

<label>opal fruits</label>

Apparently the following are all equivalent ways of matching a label based on its innerHTML value:

$("label[innerHTML=opal fruits]") - no quotes
$("label[innerHTML='opal fruits']") - single quotes within double quotes
$("label[innerHTML=\"opal fruits\"]") - escaped double quotes within double quotes


However innerHTML must be a strange one, as this form of matching only works for strings of multiple words and without the quotes.  As soon as you try and match a single word, or put quotes around the string, no matches are found.  Even more confusing is that if you try the following, which should match any element with innerHTML, you get no matches:

$("[innerHTML]")

Fortunately, jQuery, as you might expect, has a better way of doing it using the :contains(text) selector.  So now I can use the following:

$("label:contains(opal fruits)")

31 comments:

  1. Thank you for the quick and helpful tip !

    ReplyDelete
  2. Thanks for the helpful tip with the pseudo-selector :contains.

    ReplyDelete
  3. This comment has been removed by the author.

    ReplyDelete
  4. THANK you! Very helpful.

    -Rafael

    ReplyDelete
  5. What if you have another label: orange

    $("label:contains(orange)") will select both orange and oranges labels, but I only want orange to be selected

    ReplyDelete
  6. Thanks!
    I just wrote this incredible piece of code:
    $("p:contains(Slide " + n + ")").css('background-color', 'red');
    and it works!!!

    ReplyDelete

  7. Excellent article. Very interesting to read. I really love to read such a nice article. Thanks! keep rocking.Ruby on Rails Online Course India

    ReplyDelete
  8. This comment has been removed by the author.

    ReplyDelete
  9. Positive energy radiates from your post! It struck a deep chord with me. We appreciate you sharing your wise words. Go on shinning! Appreciation Power BI Certification

    ReplyDelete