Home > DeveloperSection > Articles > JQuery Traversal Method

JQuery Traversal Method


JQuery JQuery 
Ratings:
0 Comment(s)
 2301  View(s)
Rate this:

JQuery Traversal Method

In this article I have tried to explain the JQuery Traversal methods.

JQuery is a very great tool which provides a many types of DOM traversal methods which help us select elements in a document randomly as well as in sequential method.

Find Elements by index:

Below every item has its own index and we can located direct with the help of eq(index) method.

Script:

<script type="text/javascript" src="jquery-1.3.2.min.js"></script>

   <script type="text/javascript">

      $(document).ready(function() {

      $("li").eq(2).addClass("selected");

        });

   </script>

Style:

<style>

      .selected { color:red; }

      .highlight { background:yellow; }

  </style>

HTML Code:

<ul>

     <li> item 1</li>

     <li> item 2</li>

     <li> item 3</li>/*This item is second index of this list*/

     <li>item 4</li>

</ul>

Output:

JQuery Traversal Method

Find Elements by its class name:

Below is filtering the element via class name and set the style of those elements.

Script:

<script type="text/javascript" src="jquery-1.3.2.min.js"></script>

   <script type="text/javascript">

      $(document).ready(function() {

      $("li").filter(".top").addClass("selected");

      $("li").filter(".middle").addClass("highlight");

        });

   </script>

 

HTML Code:

   <ul>

     <li class="top">list item 1</li>

     <li class="top">list item 2</li>

     <li class="middle">list item 3</li>

     <li class="middle">list item 4</li>

</ul>

     

Output:

JQuery Traversal Method

Locating Tag:

Below find and filter the tag and apply the style those elements.

Script:

   <script type="text/javascript" src="jquery-1.3.2.min.js"></script>

   <script type="text/javascript">

      $(document).ready(function() {

           $("p").find("span").addClass("selected");

           $("p").filter(".paragraph").addClass("highlight");

   });

HTML Code:

<p class="paragraph">This is <span>Mindstick</span></p>

Output:

JQuery Traversal Method


Don't want to miss updates? Please click the below button!

Follow MindStick