Selecting Elements Based on What They Contain - J Query

You need to select an element based on what it contains.


There are normally only two things you would want to query in this respect: the text contents and the element contents (other elements). For the former, you can use
the :contains() filter:

Note that it’s case sensitive, so this selector wouldn’t match anything if we searched for bob (with a lowercase b). Also, quotes are not required in all situations, but it’s ago od practice just in case you encounter a situation where they are required (e.g., when you want to use parentheses).

To test for nested elements, you can use the :has() filter. You can pass any valid selector to this filter:

This selector would match all <div> elements that encapsulate <a> elements (anchors) with in <p> elements (paragraphs).


The :contains() filter might not fit your requirements. You may need more control over what text to allow and what to disallow. If you need that control, I suggest using a regular expression and testing against the text of the element, like so:

This would select all paragraphs containing the word apple, orange, or lemon. To read more about jQuery’s filter() method, have a look at Recipe 2.10.

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd Protection Status

J Query Topics