Mythriel Mythriel - 1 month ago 8
HTML Question

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?

Answer

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");
Comments