A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://developer.mozilla.org/en-US/docs/Web/API/Element/insertAdjacentElement below:

Element: insertAdjacentElement() method - Web APIs

Element: insertAdjacentElement() method

Baseline Widely available

The insertAdjacentElement() method of the Element interface inserts a given element node at a given position relative to the element it is invoked upon.

Syntax
insertAdjacentElement(position, element)
Parameters
position

A string representing the position relative to the targetElement; must match (case-insensitively) one of the following strings:

element

The element to be inserted into the tree.

Return value

The element that was inserted, or null, if the insertion failed.

Exceptions
SyntaxError DOMException

Thrown if the position specified is not a recognized value.

TypeError

Thrown if the element specified is not a valid element.

Visualization of position names
<!-- beforebegin -->
<p>
  <!-- afterbegin -->
  foo
  <!-- beforeend -->
</p>
<!-- afterend -->

Note: The beforebegin and afterend positions work only if the node is in a tree and has an element parent.

Examples
beforeBtn.addEventListener("click", () => {
  const tempDiv = document.createElement("div");
  tempDiv.style.backgroundColor = randomColor();
  if (activeElem) {
    activeElem.insertAdjacentElement("beforebegin", tempDiv);
  }
  setListener(tempDiv); // Definition in the linked GitHub demo
});

afterBtn.addEventListener("click", () => {
  const tempDiv = document.createElement("div");
  tempDiv.style.backgroundColor = randomColor();
  if (activeElem) {
    activeElem.insertAdjacentElement("afterend", tempDiv);
  }
  setListener(tempDiv); // Definition in the linked GitHub demo
});

Have a look at our insertAdjacentElement.html demo on GitHub (see the source code too.) Here, we have a sequence of <div> elements inside a container. When one is clicked, it becomes selected and you can then press the Insert before and Insert after buttons to insert new divs before or after the selected element using insertAdjacentElement().

Specifications Browser compatibility See also

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.3