Basic jQuery Tutorial: About parent and child elements

In this article, I will be explaining about parent and child elements and how to use jQuery to them efficiently.

VIEW DEMO

Basically, parent element means any HTML element with other elements inside it. Like in the following HTML code, we have the div ‘parent’. We suppose it to be parent element. There are other elements inside it like ul, li, and span. So, ul, li and span are children of the div ‘parent’. There is also nested ul and li, hence containing parent child combination.

<div>
	Hover the box and LINK! <br /><br />
	<ul>
		<li>LINK 1 
			<ul>
				<li>Sub link 1</li>
				<li>Sub link 2</li>
				<li>Sub link 3</li>
			</ul>
		</li>
		<li>LINK 2
			<ul>
				<li>Sub link 1</li>
				<li>Sub link 2</li>					
			</ul>
		</li>
	</ul>
	<br />
	<span>Sample text One!</span> <br />
	<span>Sample text Two!</span> <br />		
	<span>Sample text Three!</span> <br />
</div>

The following jQuery code will change the CSS of all span inside the div with id ‘parent’ when we hover the mouse over the div.

jQuery(‘parent > child’) description: Selects all direct child elements specified by “child” of elements specified by “parent”.

$("#parent").hover(function(){
	$("#parent &gt; span").css({"color":"green","font-size":"20px"});
}, function(){
	$("#parent &gt; span").removeAttr("style");
});

The following jQuery code will change the CSS of the parent of li inside the div with id ‘parent’ when we hover the mouse over the li element of the div.

More clearly explaining:
- when mouse is hovered on the li element of the div with id ‘parent’
- then the CSS of the parent of the particular li element is change (not of the li element but of the parent of the li element)
- when the mouse is moved away from the li element, then the recently added css is removed and we go back to normal
- parent() function description: Get the parent of each element in the current set of matched elements.

$("#parent li").hover(function(){
	$(this).parent().css({"border":"1px solid red"});
}, function(){
	$(this).parent().removeAttr("style");
});


VIEW DEMO

Cheers,

1 Comment Basic jQuery Tutorial: About parent and child elements

  1. Pingback: Design Gala

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>