jQuery – :has() Selector

The jQuery has selector selects elements which contain at least one element that matches the specified selector.

Source Code

<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<div id="div1">
<div><h4>Text 1</h4></div>
<div><h5>Text 2</h5></div>
</div>
<button>Click Here</button>

  
<script>
jQuery("button").click(function () {
	jQuery("#div1 div:has(h4)").css({border:"3px #1E8CBE solid"});
});
</script>
</body>
</html>

The expression jQuery(‘div:has(h4)’) matches a <div> if a <h4> exists anywhere among its descendants, not just as a direct child.

Demo

Following example adds a border around all DIV that have a H4 element inside of them.

Text 1

Text 2

,

No comments yet.

Leave a Reply