Lesson 5 – Document Traversing

DOM traversing is a method of locating elements sequentially as well as randomly in a document. There are dedicated methods to perform each of these functions. The point to remember here is that you cannot use any DOM traversal method to modify the objects in jQuery. Their sole purpose is to filter out elements from a document according to a given condition.

For example, you can use the eq(index number) method to easily filter out elements using their index numbers as shown in the following example.

<!DOCTYPE html>
<html lang="en">
<head>
    <title>DOM Traversing</title>
    [block]0[/block]


    
       $(document).ready(function() {
            $('li').eq(3).addClass("changed");
         });
     

     <style>
        .changed {
           color: aqua;
        }
     </style>
</head>
<body>
   
  • First item on the list
  • Second item on the list
  • Third item on the list
  • Fourth item on the list
  • Fifth item on the list
  • Sixth item on the list
</body> </html>

In the above example, we have selected the fourth item in the unordered list and add a class named “changed” to it. Subsequently, we have changed the text color of the fourth item by adding styles to the “changed” class.

The browser will transform the above code as under.

Sometimes, you also need to filter out elements that don’t match the selectors in a group of matched elements. You can accomplish this task by using the filter(selector) method.

In the following example, we apply colors to the paragraphs only with the “color” class and filter out every other paragraph element.

“`

Here is the output of the above piece of code.

In the next lesson, we will discuss DOM Manipulation in jQuery.