Jquery Selector: Find nested/child elements

Using jquery you get great level flexibility to search Dom elements using selectors. This article explains in Jquery to Find elements inside an element. 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(). If you want the details about hash selector you may visit jQuery Id/Hash (#) Selector With Examples

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 🙂 This is how you to find Jquery Find elements inside an element.

Please share this post:
Distinguished Engineer Java, PHP, Spring, Mysql
Posts created 11

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

  1. Pingback: How to get only direct child elements by jQuery function – inneka.com
  2. 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!

Ask a Question

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Posts

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

%d bloggers like this: