5

I have the following markup: <ul class="list"> <li>4</li> <li>5</li> <li>6</li> </ul>

How can I select the li items with the html value of 5 and 6 and add a class to them?

1
  • 2
    maybe this post will help? Commented Feb 28, 2012 at 17:55

5 Answers 5

12

One option is the :contains selector...

$("li:contains(5),li:contains(6)").addClass("myClassName"); 

However, since it's just looking for that text and not matching the entire contents, that will also match <li>56</li>, <li>16</li>, and so on.

So, what you probably ought to do instead is use .filter() like so:

$("li").filter(function () { var text = $(this).text(); return text === "5" || text === "6" }).addClass("myClassName"); 
Sign up to request clarification or add additional context in comments.

1 Comment

Just be aware that this will also select list-items that contain 56 or 5.1 or anything that contains one of those single numbers.
4

You can use .filter():

//setup object of the characters we want to match (we will be matching the keys, not values) var whitelist = { 5 : 0, 6 : 0 }; //select all the list-item elements and filter them var $selectedElements = $('.list').children().filter(function () { //returns true if the text of this element is one of the keys in the `whitelist` variable return ($(this).text() in whitelist); }); 

If you return true the element will be kept in the set of elements, if you return false then it will be removed from the set.

This matches the whole text of the element, it doesn't just check if the text contains a character.

Here is a demo: http://jsfiddle.net/jasper/ndcFg/2/

Comments

3

use :contains() Selector

$("li:contains('5')") 

2 Comments

This will only work for the very simple case with only single digit numbers.
I wouldn't down-vote, but you should warn that this will match any string or number that has a 5 in it, like 50 or 5.0.
0
$("ul.list li").each(function(){ if( $(this).text() == '5' || $(this).text() == '6' ) { $(this).addClass('theClass'); } }); 

Comments

0

I suspect the demo is far too over simplified... and that by "value" you mean text

$('.list li').filter(function(){ var txt=$(this).text(); return txt==='4' || txt==='5'; }).addClass('someclass'); 

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.