How to traverse and manipulate the DOM tree with jQuery?

To traverse and manipulate the DOM tree with jQuery, you can use the following methods:

  1. Selecting elements:

    • $(selector): Selects elements based on the selector. This returns a jQuery object containing matched elements.
  2. Traversing the DOM tree:

    • .children(): Gets the direct children of each element in the set of matched elements.
    • .parent(): Gets the parent of each element in the set of matched elements.
    • .find(): Finds descendant elements that match the selector.
    • .siblings(): Gets the siblings of each element in the set of matched elements.
  3. Manipulating elements:

    • .text(): Sets or gets the text content of matched elements.
    • .html(): Sets or gets the HTML content of matched elements.
    • .attr(): Sets or gets an attribute value of the first matched element.
    • .addClass(): Adds one or more classes to the matched elements.
    • .removeClass(): Removes one or more classes from the matched elements.
  4. Manipulating element properties:

    • .prop(): Sets or gets a property value of the first matched element.
  5. Using CSS:

    • .css(): Sets or gets the CSS properties of the matched elements.
  6. Taking actions:

    • .on(): Attaches an event handler function for the selected elements.
    • .trigger(): Triggers a specified event on the selected elements.

Here's an example of traversing and manipulating the DOM tree with jQuery:

// Selecting elements $('.parent').children('.child').addClass('highlighted'); // Traversing the DOM tree $('.element').parent().addClass('highlighted'); $('.element').find('.descendant').addClass('highlighted'); $('.element').siblings().addClass('highlighted'); // Manipulating elements $('.element').text('New text'); $('.element').html('<p>New content</p>'); $('.element').attr('data-id', '123'); // Manipulating element properties $('.checkbox').prop('checked', true); // Using CSS $('.element').css('color', 'red'); // Taking actions $('.button').on('click', function() { // Do something... }); $('.element').trigger('click');

These are just some of the methods available in jQuery to traverse and manipulate the DOM tree. The jQuery documentation provides a comprehensive list of methods and examples for further reference.