Ad Code



How to use closest and parent in jquery


How to use closest and parent in jquery

In jquery have many javascript built-in functions which you can use in the Html web page for traversing dom, change styles, animations, and event handling. The closest() and parent() functions are used to get the ancestor's element of the current elements. Both functions use the same but some dereferences are involved.

  1. parent():- this function returns the immediate ancestor only if it matches the selector specified.
  2. closest():- however closest() function search all ancestors and returns only first matches the selector specified.
In the parent function, you never know the dom structure if always return the immediate parent but the closest() function may be required to know the structure if you want to perform any ancestors of the current elements.

For example here have some Html code and I have implemented the parent and closest function both in the same elements.

<div class="parent_div">
	<button type="button" data-reset>Reset</button>
		<li><button type="button" data-color="red">Red</button></li>
		<li><button type="button" data-color="green">Green</button></li>
		<li><button type="button" data-color="blue">Blue</button></li>

This Html code has two types of buttons first one is the reset parent div bg-color and all ul buttons set color according to the specified value in the data-color field.

Using closest() to set bg-color:-

The closest function is used in the button of the ul buttons because it has many ancestors like li then ul then the parent div which wants to perform change background color.

		var color = $(this).data("color");

In this code, I have used attribute as a selector of the elements you can also use as a won choice.

This function is to click on the color button to find the parent_div class of the closest ancestors and set the style attribute in the elements.

The change background color according to the defined color inside attribute data-color as defined to set CSS function in the code.

Using parent() to reset bg-color:-

The first button click to reset the parent background color because this is the first child of the parent_div then it can be used parent function to find immediate ancestors like bellow:-


This function is used to first get the parent element and remove the set CSS function style attribute then it will same as the previous Html code.

The above code you can use as your requirements like if you want to get immediate parent then you can use parent() function but if you want to the specific level of the parent with selector then you use the closest() function.

Post a Comment


Ad Code