Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - contents equal to rather than contents contains

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?

like image 838
Andrew Rasmussen Avatar asked Dec 30 '11 07:12

Andrew Rasmussen


People also ask

How do I check if a div contains a text?

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.

How use contains in jQuery?

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).

Can we use multiple selectors in jQuery?

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.

What is used to obtain the HTML innerHTML contents of the first matched element?

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.


1 Answers

$('#group ul li div.category').filter(function() {return $(this).text() == "one";}).parent()

This is probably the most specific way. See example.

like image 160
Ilia G Avatar answered Oct 07 '22 00:10

Ilia G