Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select an element based on its html value in jQuery

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?

like image 263
Mythriel Avatar asked Feb 28 '12 17:02

Mythriel


1 Answers

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");
like image 127
canon Avatar answered Nov 15 '22 05:11

canon