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>
	<title>My site</title>
	<script src="jquery-3.2.1.min.js"></script>
		.conclusion {
			font-size: 0.7em;
		.red {
			color: red;

<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">
			<a href="http://dan.saigon.ro">My website contains:</a>
				<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>
		<li>I have other websites as well
				<li>About chemistry website</li>
				<li>About Math website</li>

	var $allElements = $('*');


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