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:

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


// 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 =)



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.