jQuery – Select elements with or without specific child

In jQuery, the has() method allow us to reduce the set of matched elements which only contains the specified child. For example:

<ul>
  <li>list item 1</li>
  <li>list item 2
    <ul>
      <li>list item 2-a</li>
      <li>list item 2-b</li>
    </ul>
  </li>
  <li>list item 3</li>
  <li>list item 4</li>
</ul>

 

// Set background color to red to the li which contains ul
$("li").has("ul").css("background-color", "red");

 

Alternatively, if you want to select the specific li which doesn’t contains ul, try the following:

// Set background color to blueto the li which DOES NOT contain ul
$("li").not(":has(ul)").css("background-color", "blue");

 

Done =)

Reference:

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.