Home  >  jQuery

Example of .closest() in jQuery

April 29, 2013
.closest() takes selector as input. We need to provide any DOM element. .closest() begins with current element and travels up to the DOM element to find the given selector. Find the syntax.
.closest(Selector)
 
Selector can be any DOM element. Find the example.

<!DOCTYPE html>
<html>
<head>
<style>
p { margin: 3px; background:yellow }
p.change { background: red; }
</style>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<p>First line: click here</p>
<p>Second line: click here</p>
<script>
$( document ).on("click", function( elm ) {
$( elm.target ).closest("p").toggleClass("change");
});
</script>
</body>
</html>
 

Output
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us