jQuery has() method

The jQuery has() method used to return all elements having one or more than one elements inside them that match the given selector. We have to use a comma if we have to select elements, including several elements inside them.

Syntax

The selector in the above syntax is the element to select and return the matching element in it. It can be a tag name, class name or an id of the element.

The has() method accepts a single parameter, which is defined as follows -

element: It is the mandatory parameter that can be an element or a selector expression to match the elements against.

Now, let's understand the working of jQuery has() method by using some illustrations.

Example1

In this example, we are using the has() method to select the div element that has the heading h3 inside it. Here, there are multiple div elements containing different children, but the method will only select the div containing heading h3. We have to click the given button to see the working of the has() method.

Test it Now

Output

After the execution of the above code, the output will be -

jQuery has() method

After clicking the given button, the output will be -

jQuery has() method

Example2

It is another example of using the has() method. Here, we are specifying multiple selectors separated by a comma. The has() method will select the elements given in the selector only when they have a span element inside them.

Test it Now

Output

After the execution of the above code, the output will be -

jQuery has() method

After clicking the given button, the output will be -

jQuery has() method

Example3

In this example, the has() method will return the elements that have multiple elements inside them. The method will return only those p, h5, and h4 elements that has either <span> element with id = "span1" or <b> element.

Test it Now

Output

After the execution of the above code, the output will be -

jQuery has() method

After clicking the given button, the output will be -

jQuery has() method




Latest Courses