Select Child and Siblings using jQuery

Title

Select Child and Siblings using jQuery

Introduction

In this post we’ll see how to select Child and Siblings using jQuery, here as an example we will be using div tag as a parent tag and p tag as a child and siblings.

Here we will see how we can select first child and first sibling using jQuery and also how to select a particular child or sibling.

See below code

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
 <title>Test</title>
 <script src="script/jQuery.min.js"></script>
 <script>
 function test() {
 $('p').css("font-size", "3em");
 $('div>p:first').css("color", "red");
 $('div>p:eq(1)').css("color", "blue");
 $('div>p:eq(2)').css("color","green")
 $('div~p:eq(0)').css("color", "orange");
 $('div~p:eq(1)').css("color", "purple")
 $('div~p:eq(2)').css("color", "brown")
 }
 </script>
</head>
<body onload="test()">
 <div>
 <!-- Childs of div -->
 <p>
 JAVA
 </p>
 <p>
 PHP
 </p>
 <p>
 C-Sharp
 </p>
 </div>
 <!-- Siblings of div -->
 <p>
 JavaScript
 </p>
 <p>
 jQuery
 </p>
 <p>
 C++
 </p>
</body>
</html>

 

If you see test() method in the above code,





function test() {
$('p').css("font-size", "3em");
$('div&gt;p:first').css("color", "red");
$('div&gt;p:eq(1)').css("color", "blue");
$('div&gt;p:eq(2)').css("color","green")
$('div~p:eq(0)').css("color", "orange");
$('div~p:eq(1)').css("color", "purple")
$('div~p:eq(2)').css("color", "brown")
}

To select first child, here “div” is the parent node and “p” is the child node, we have two ways


$('div&gt;p:first').css("color", "red");

$('div&gt;p:eq(0)').css("color", "red");

We can use any of the way, and same goes for selecting siblings.

$(‘div~p:eq(0)’).css(“color”, “orange”);

$(‘div~p:first’).css(“color”, “orange”);

[\code]

You can use either of the way.

OUTPUT

jquery


JavaScript, ASP.Net & PHP Web Developer. Connect with me on Facebook and Twitter.

Share This Post

Related Articles

Powered by Paras Babbar · Designed by Paras Babbar