Reputation: 1380
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?
Upvotes: 5
Views: 5901
Reputation: 41715
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");
Upvotes: 12
Reputation: 76003
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/
Upvotes: 4
Reputation: 171690
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');
Upvotes: 0
Reputation: 3323
$("ul.list li").each(function(){
if( $(this).text() == '5' || $(this).text() == '6' ) {
$(this).addClass('theClass');
}
});
Upvotes: 0