PHP, MySQL, & JavaScript All-in-One For Dummies
Book image
Explore Book Buy On Amazon
Not only can you use jQuery to modify content and styles of the existing elements in your web page, you can also use it to add or remove entire elements! There are a handful of different jQuery functions available for manipulating the element nodes contained in the DOM tree.

Adding a node

You can use jQuery to add a new node to the DOM tree to display additional content as needed. This table shows the functions available for adding new nodes.
The jQuery Functions to add DOM Nodes
Function Description
.after() Adds a node after an existing node
.append() Adds a node to the end of an existing node
.appendTo() Adds a new node to the end of an existing node
.before() Adds a node before an existing node
.insertAfter() Adds a new node after an existing node
.insertBefore() Adds a new node before an existing node
.prepend() Adds a node to the beginning of an existing node
.prependTo() Adds a new node to the beginning of an existing node
Note the subtle difference between the .after() and .append() functions. The .append() function adds the new node to the end of the existing node, so it becomes a child node of the existing node in the DOM. The .after() function, on the other hand, adds a new sibling node after the existing node in the DOM. Likewise for the .before() and .prepend() functions.

For example, you can add a new p element to the existing p element in your example program by adding the following code:

$("p").after("<p>This is a new node</p>");
As you would expect, when you run one of these functions, the new node immediately appears in the web page.

Removing a node

The jQuery library provides two functions for you to remove existing nodes from the DOM:
  • empty(): Removes all child nodes from the specified node
  • remove(): Removes the specified node
It's important to note that the .empty() function doesn’t remove the specified node — it just removes any child nodes associated with the node.

About This Article

This article is from the book:

About the book author:

Richard Blum has more than 30 years of experience as a systems administrator and programmer. He teaches online courses in PHP, JavaScript, HTML5, and CSS3 programming, and authored the latest edition of Linux For Dummies.

This article can be found in the category: