jquery
  1. jquery-traversing-introduction

Introduction to jQuery Traversing

jQuery Traversing is a set of methods used to navigate and manipulate the DOM (Document Object Model) of a webpage. It allows you to traverse and manipulate the HTML elements of a webpage based on their relationship to other HTML elements.

Syntax

The syntax for jQuery Traversing is as follows:

$(selector).traverse-method()

Here, selector is the HTML element you want to select and traverse-method is the traversing method you want to use to navigate through the DOM.

Use

jQuery Traversing is used to easily move and manipulate HTML elements on a webpage. It allows you to easily select, filter, and manipulate elements based on their relationships to other HTML elements on the page.

Example

Here is an example of using jQuery Traversing to select and manipulate HTML elements on a webpage:

<html>
<head>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>

  <ul class="list">
    <li>Item 1</li>
    <li class="active">Item 2</li>
    <li>Item 3</li>
    <li class="active">Item 4</li>
    <li>Item 5</li>
  </ul>

  <script>
    $(document).ready(function() {
      
      // Find all active items and add class "highlight"
      $(".list li.active").addClass("highlight");
      
      // Display the text of the first list item
      var firstItem = $(".list li:first-child").text();
      console.log(firstItem);
  
      // Find all list items and change their text color
      $(".list li").css("color", "red");
  
      // Find the parent of the active item and change its background color
      $(".list li.active").parent().css("background-color", "lightblue");
  
    });
  </script>

</body>
</html>
Try Playground

In this example, we use jQuery Traversing methods to add a class to all active list items, display the text of the first list item, change the text color of all list items, and change the background color of the parent element of the active list item.

Summary

jQuery Traversing is a powerful tool that can be used to navigate and manipulate the DOM of a webpage. With its wide range of methods, it allows you to easily select, filter, and manipulate HTML elements based on their relationships to other elements on the page. Try it out for your next project!

Published on: