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.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 |
.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 noderemove()
: Removes the specified node
.empty()
function doesn’t remove the specified node — it just removes any child nodes associated with the node.