Given the following html...
<div id="group">
<ul>
<li><div class="category">one</div></li>
<li><div class="category">one</div></li>
<li><div class="category">onetwo</div></li>
<li><div class="category">two</div></li>
</ul>
</div>
...I'm trying to figure out how to make a selector in jQuery that will select all '#group ul li'
elements that have a child '.category'
with innerHTML equal to some string (eg. "one"). For example, given the string "one", this selector would return the first two li's.
Here's what I have so far:
$('#group ul li')
will select all of the li's. Then I need to filter:$('#group ul li').filter(".category:contains('one')")
will select all of these li's such that they have a child with class category that contains the string 'one'. However, is there any way to check that this is equal to one?
I'm thinking maybe just write my own function that does the equality check and pass that to filter?
To check if a div element contains specific text:Use the textContent property on the element to get the text content of the element and its descendants. Use the includes() method to check if the specific text is contained in the div . If it is, the includes() method returns true , otherwise false is returned.
The :contains() selector selects elements containing the specified string. The string can be contained directly in the element as text, or in a child element. This is mostly used together with another selector to select the elements containing the text in a group (like in the example above).
You can specify any number of selectors to combine into a single result. This multiple expression combinator is an efficient way to select disparate elements. The order of the DOM elements in the returned jQuery object may not be identical, as they will be in document order.
jQuery html() Method The html() method sets or returns the content (innerHTML) of the selected elements. When this method is used to return content, it returns the content of the FIRST matched element.
$('#group ul li div.category').filter(function() {return $(this).text() == "one";}).parent()
This is probably the most specific way. See example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With