02 – Retrieving elements by their hierarchy in jQuery

You may want to retrieve only the direct child of a certain element. To exemplify this we have to add a list (actually a list within another list) to our page. Here is what we have so far.

<!DOCTYPE html>
<html>
<head>
	<title>My site</title>
	<script src="jquery-3.2.1.min.js"></script>
	<style>
		.conclusion {
			font-size: 0.7em;
		}
		.red {
			color: red;
		}
	</style>
</head>
<body>

<div class="main-div">
	<h3>I am a header</h3>
	<p>I'm a paragraph</p>
	<p class="conclusion">This is a conclusion</p>
	<p class="conclusion red">This paragraph is a red conclusion</p>
	<img id='my-img' src='dan.jpg' alt="Dan pic">
	<ul class="list-one">
		<li>
			<a href="http://dan.saigon.ro">My website contains:</a>
			<ul>
				<li><a href="http://dan.saigon.ro/about/">About Page</a></li>
				<li><a href="http://dan.saigon.ro/portfolio/">Portfolio Page</a></li>
				<li><a href="http://dan.saigon.ro/contact/">Contact Page</a></li>
				<li>And many other pages</li>
			</ul>
		</li>
		<li>I have other websites as well
			<ul>
				<li>About chemistry website</li>
				<li>About Math website</li>
			</ul>
		</li>
	</ul>
</div>

<script>
	var $allElements = $('*');
</script>

</body>
</html>

Let’s say that you want just to select the <a> element pointing to http://dan.saigon.ro website but not those to the local pages. To do this you can use the Child selector, in which a parent and its direct child are separated by the right angle bracket character (>).

ul.list-one > li > a

This selector will collect only links that are direct children of list elements, which are in turn direct children of the <ul> that have class list-one. The links contained in the sub-lists are excluded because the ul element serving as their parent doesn’t have the class list-one.

Leave a Reply