jQuery

jQuery :parent Selector Examples

The jQuery parent selector basically select all elements that that have at least one child node. This child node could be either an element or text. That said, we will see how to use the :parent selector by means of easy to follow examples. Read on to find out more.

How to use the jQuery parent Selector

In order to see how to use the parent selector, let us assume that we have few different elements on a web page, such as nested divs, paragraph tag, span tag, hyperlink, etc. So let’s see different combinations of using the parent tag and how it can be used to manipulate the DOM elements.

Example 1: Find parent of MY DIV 1 and alert the result when a button is clicked

	$('#sbt_find_mydiv1_parent').on("click", function(e){			

		if( $('.divs_container #my_div1').parent('div').length )
		{
			alert('MY DIV 1 has a parent Div.');	
		}
		else
		{
			alert('MY DIV 1 DOES NOT have a parent Div.');	
		}

		e.preventDefault();

	});

Example 2: Find parent of MY DIV 4 and add GREEN class to it when a button is clicked

	$('#sbt_find_mydiv4_parent').on("click", function(e){		

		$('.divs_container #my_div4').parent('div').addClass('green');

		e.preventDefault();

	});

Example 3: Find parent of MY DIV 6 and remove all classes from it when a button is clicked

	$('#sbt_find_mydiv6_parent').on("click", function(e){		

		$('.divs_container #my_div6').parent('div').removeClass();

		e.preventDefault();

	});

Example 4: Add “red_text” class to all paragraphs  using the Parent Child Selector when a button is clicked

	$('#sbt_parent_child_selector').on("click", function(e){		

		$(".divs_container > p").addClass('red_text');		

		e.preventDefault();

	});

Example 5: Change href source of all hyperlinks when a button is clicked

	$('#sbt_change_href').on("click", function(e){			

		$(".divs_container a").prop("href", "https://theextremewebdesigns.com/blog/");

		alert('New HREF source for all hyperlinks is https://theextremewebdesigns.com/blog/');

		e.preventDefault();

	});
Simple, isn’t it?

Do you know of any other ways to use the jQuery parent selector? Feel free to suggest by commenting below.

Share your thoughts, comment below now!

*

*