JQuery Child Selector Example

JQuery child selector selects all the elements that are child of parent element in the set of matched elements. It represents the child element which is obtained from selector. It selects all the child elements that are defined by parent selector.  The child selector searches for children elements in the document object model structure and constructs new object from the set of matching elements. The child selector accepts the elements that are of same type that we can pass to the $() function. It’s written using greater than symbol (>) and it must appear between two other selectors.

JQuery Child Selector Syntax

(“parent>child”)

It ha parameter called parent is a required parameter which defines valid parent selector which defines the parent element to be selected and child is a required parameter which defines child element to be selected.

JQuery Child Selector Example

<!doctype html>
<head>
<title>JQuery Child Selector</title>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<h2>JQuery Child Selector Example</h2>
<script type="text/javascript">
   $(document).ready(function(){
      $( "div.myclass > span" ).css("border","2px groove orange");
   });
</script>
<body>
   <div class="myclass">
      <span>This is first span.
      <span>This is second span.</span>
      </span>
   </div>
   <span>This is third span.</span>
</body>
</html>
  • As shown in the above program, we have used the code inside $(document).ready which is an event which fires up when document is ready. It will run once the page document object model is ready for JavaScript code to execute.
  • $( “div.myclass > span” ).css(“border”,”2px groove orange”); line defines child selector which selects the elements are direct child of specified element. It matches only those elements matched by second selector which are children’s of elements matched by the first.
  • When we run the above script, the matched elements will get display with grooved border and orange color.

JQuery Child Selector Demo

When you run the above example, you would get the following output:

JQuery Child Selector Example

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*