jQuery – :has() Selector

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

Source Code

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

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

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


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