2

I have this li list:

<ul>
  <li>item 1</li>
  <li>item 2</li>
  <li>item 3</li>
  <li>item 4</li>
  <li>item 5</li>
</ul>

How can I add a class "item-3" to the li element that contains "item 3" between the <li> and </li> tags?

Thanks in advance.

0

5 Answers 5

14
$('li:contains("item 3")').addClass('item-3');

From the docs (http://api.jquery.com/contains-selector/):

The matching text can appear directly within the selected element, in any of that element's descendants, or a combination thereof. As with attribute value selectors, text inside the parentheses of :contains() can be written as bare words or surrounded by quotation marks. The text must have matching case to be selected.

Here's a jsfiddle: http://jsfiddle.net/jasper/2wcqW/

Sign up to request clarification or add additional context in comments.

1 Comment

Just as a side-note: the :contains() selector is case-sensitive. Case-insensitive searches require .filter() and a custom function.
5
$('li').filter(function(){
    return $(this).text() === 'item 3'
}).addClass('yourClass');

1 Comment

+1 FWIW, this is the fastest method between: :contains(), $.each() and .filter(). Here's some proof: jsperf.com/jquery-each-vs-contains
3

Try the following

$(document).ready(function () {
  $('ul li').each(function () {
    if ($(this).text() === "item 3") {
      $(this).addClass('item-3');
    }
  });
});

Fiddle: http://jsfiddle.net/srpAX/

4 Comments

+1 FWIW; This is faster than using :contains. Here is a jsperf to prove: jsperf.com/jquery-each-vs-contains
@Jasper I'd never seen that sight before. Amazing.
Is filter ALWAYS the fastest way to do this kind of task or is it situation specific?
@Zero21xxx I couldn't say off the top of my head. I generally use jsperf in a specific situation to see what is the fastest method. Something to remember is that different browsers will give different results and this is especially true with old browsers (...IE6).
2
$('li:contains("item 3")').addClass('item-3');

1 Comment

will work correctly, but I do not think it is necessary to first select on ULs
1
$("li").each(function(){
    if($(this).text() == "Item 3"){
        $(this).addClass("item-3");
    }
});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.