How to traverse Data Object Model (DOM) nodes using jQuery?


jQuery traversing is used to find elements based on what is their relation twith other elements. You need to begin with one selection and move ahead till you the reach the elements you want.

jQuery is a very powerful tool which provides a variety of DOM traversal methods to help us select elements in a document randomly as well as in sequential method.

Let’s filter out the elements by traversing. The filter( selector ) method can be used to filter out all elements from the set of matched elements that do not match the specified selector(s).

Example

The selector can be written using any selector syntax.

Live Demo

<html>

   <head>
      <title>The JQuery Example</title>
      <script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
       
      <script>
         $(document).ready(function() {
            $("li").filter(".middle").addClass("selected");
         });
      </script>
       
      <style>
         .selected {
            color:blue;
          }
      </style>
   </head>
   
   <body>
   
      <div>
         <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>
            <li class = "bottom">list item 5</li>
            <li class = "bottom">list item 6</li>
         </ul>
      </div>
       
   </body>
   
</html>

Updated on: 18-Dec-2019

215 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements