Lesson 18

jQuery Traversal and Manipulation

In the previous lesson, you learned how to select elements from the DOM with jQuery. This lesson will build on that knowledge and teach you how to:

  • Traverse from those elements to another set of related elements.
  • Manipulate the nodes in the DOM—this includes adding new nodes, modifying ­existing nodes, and removing nodes from the DOM.

Traversal

When you execute a jQuery selection, the result is a jQuery object encapsulating a set of ­elements. The traversal operations allow you to traverse from the initially selected elements to a new set of elements. The result of a traversal is therefore also a jQuery object encapsulating a set of elements.

You have already seen one instance of a traversal operation: the find method in the previous lesson was a traversal operation because it began by finding an element (or set of elements), and then finding other elements that are children of these elements.

It is also possible to traverse from elements to their parents. For instance, the following starts by finding all the time elements, and then finds their parents, which are td elements:

> $('time').parent();

This will return two td elements.

The parent function returns immediate parents; if you want to find elements that are indirect parents, you can use the parents function. This returns any element that is an ancestor of the selected elements, but it is possible to provide a selection to this function as a parameter. For instance, you ...

Get HTML5, JavaScript, and jQuery 24-Hour Trainer now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.