Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use jQuery :has() and :contains() selectors together

I have a list item element that contains a label element. I want to select the list item element with the :has() selector. Inside the label element there is text I want to match with :contains(). Is it possible to do both of these things with a single line of jQuery? If not, what is an elegant way to select the li element based on the contents of its child label element?

<li>
    <!-- I want to select this one -->
    <label>Label 1</label>
    <!-- more follows -->
</li>
like image 964
Keyslinger Avatar asked Sep 09 '13 00:09

Keyslinger


1 Answers

You want either:

$("li:has(label):contains('Label 1')")

This will select any <li> that both has a <label> and contains the text Label 1 anywhere inside of it.

$("li:has(label:contains('Label 1'))")

This will select any <li> that has a <label> and that label in particular contains the text Label 1. (The first selector will match if "Label 1" is anywhere inside the <li>.)

like image 102
apsillers Avatar answered Sep 18 '22 02:09

apsillers