Jquery Selector: Find nested/child elements

Using jquery you get great level flexibility to search Dom elements using selectors. There are many selectors but two of then are broadly used 1. Hash Selector 2. Dot selector.

Hash (#) selectors search element with id. This is equivalent to a native javascript method document.getElementById()

Dot selector search elements with class name.

There are often situations where we want to combine both selectors. Here in this article, we are going to discuss complex scenarios like how to get an element inside of div.

Find a direct span inside a div

<div id="parent">
<span id="one">One</span>
<span id="two">Two</span>
<script>var spanTwoTet = $("#parent > #two").text()</script>

As the above selector searches for the direct child below code will not work.

<div id="parent">
	<div id="child">
		<span id="three">Three</span>
	<span id="one">One</span>
	<span id="two">Two</span>
alert($("#parent > #three").text());

So, how to solve the above problem? Using the find method https://api.jquery.com/find/

$("#parent").find("#three").text(); // This will get "Three"

Find is very flexible and you may use a lot of different selectors to search in DOM hierarchy. Below code will count all the span within a div.

$("#parent").find("span").length // This will get 3 as there are three span in side div parent.

Enjoy 🙂

Distinguished Engineer Java, PHP, Spring, Mysql
Posts created 5

3 thoughts on “Jquery Selector: Find nested/child elements

  1. Hello! I could have sworn I’ve been to this blog before but after browsing through some of the post I realized it’s new to me. Anyways, I’m definitely happy I found it and I’ll be book-marking and checking back frequently!

Leave a Reply

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

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.