Adding Adjacent Elements

In this lesson, we will add adjacent elements in the document tree.

We'll cover the following

To extend the document tree, it is not enough to add child nodes to HTML elements. You also need to add sibling elements and text to existing HTML tags. Unfortunately, the HTML DOM standard does not contain any method that can be used to add sibling nodes directly before or after a certain document tree node.

A few browser vendors extend the standard DOM API with extra operations.

For example, Google Chrome, Opera, Safari, and Internet Explorer provide three additional methods, insertAdjacentText(), insertAdjacentElement(), and insertAdjacentHTML() which can be used for this task.

Firefox does not implement these operations. In this section, you will learn how to use them.

Listing 6-9 demonstrates using insertAdjacentText(). This code wraps every link in the page with square brackets, adding a “[” character before, and another “]” character after the link with insertAdjacentText().

Get hands-on with 1200+ tech skills courses.