jQuery has() Method
The jQuery has() method is a powerful way to select elements that contain a specific child element or set of child elements. This method can be a very useful tool in manipulating or accessing targeted elements on a web page.
Syntax
The basic syntax for using the has() method is as follows:
$('parent_selector').has('child_selector');
Where parent_selector
is the selector for the parent element and child_selector
is the selector for the child element.
Use
The has() method is used to select elements based on whether or not they contain a specific child element or set of child elements. This can be useful if you need to manipulate or access only those elements that have a certain child rather than modifying all elements on the page.
Example
Consider the following HTML structure:
<div class="parent">
<h2>Title</h2>
<p>Some content here</p>
</div>
<div class="parent">
<h2>Title 2</h2>
<ul>
<li>Item 1</li>
<li>Item 2</li>
</ul>
</div>
We may want to select all .parent
elements that contain a ul
element inside them. We can do that by using the has() method:
$('.parent').has('ul').css('border', '1px solid red');