jquery
  1. jquery-has

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');

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>jQuery Example</title>
  <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
</head>
<body>

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

  <script>
$('.parent').has('ul').css('border', '1px solid red');

  </script>

</body>
</html>
Try Playground

In this example, we select all .parent elements that have a ul element inside them, and then we apply a CSS border style to those elements.

Summary

The jQuery has() method is a powerful tool for selecting elements that contain a specific child element or set of child elements. It can be useful for accessing and manipulating only those elements that have a certain child element rather than modifying all elements on a page. Give it a try in your next jQuery project!

Published on: