Skip to content

Make insertAdjacentElement example a live example in the page #39443

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
112 changes: 92 additions & 20 deletions files/en-us/web/api/element/insertadjacentelement/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,31 +68,103 @@ The element that was inserted, or `null`, if the insertion failed.

## Examples

### Inserting before and after

In this example we have a row of square boxes. The user can select a box by clicking on it: this gives the box a different border, to show that it is selected.

If a box is selected, and the user presses the "Insert before" or "Insert after" buttons, then the code creates a new box, gives it a random color, and inserts it before or after the selected box.

#### HTML

```html
<p>
Click colored box to select it, then use the first two buttons below to insert
elements before and after your selection.
</p>

<section>
<div></div>
<div></div>
<div></div>
<div></div>
</section>

<button class="before">Insert before</button>
<button class="after">Insert after</button>
<button class="reset">Reset demo</button>
```

#### CSS

```css
div {
width: 50px;
height: 50px;
margin: 3px;
border: 3px solid black;
display: inline-block;
background-color: red;
}

.selected {
border-color: aqua;
}
```

#### JavaScript

```js
beforeBtn.addEventListener("click", () => {
const tempDiv = document.createElement("div");
tempDiv.style.backgroundColor = randomColor();
if (activeElem) {
activeElem.insertAdjacentElement("beforebegin", tempDiv);
let selectedElem;

// Function to select a new element
function selectElement(newSelection) {
if (selectedElem !== newSelection) {
if (selectedElem) {
selectedElem.classList.remove("selected");
}
selectedElem = newSelection;
newSelection.classList.add("selected");
}
}

// Add click handlers that select the clicked element
const initElems = Array.from(document.querySelectorAll("section div"));
for (const initElem of initElems) {
initElem.addEventListener("click", (e) => selectElement(e.target));
}

// Add click handlers to "beforeBtn" and "afterBtn"
// to insert a new element before/after the selected element
const beforeBtn = document.querySelector(".before");
const afterBtn = document.querySelector(".after");
beforeBtn.addEventListener("click", () => insertNewElement("beforebegin"));
afterBtn.addEventListener("click", () => insertNewElement("afterend"));

function insertNewElement(position) {
function random() {
return Math.floor(Math.random() * 255);
}
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);

if (!selectedElem) {
return;
}
setListener(tempDiv); // Definition in the linked GitHub demo
});

const newElement = document.createElement("div");
const randomColor = `rgb(${random(255)} ${random(255)} ${random(255)})`;
newElement.style.backgroundColor = randomColor;
newElement.addEventListener("click", (e) => selectElement(e.target));

selectedElem.insertAdjacentElement(position, newElement);
}

// Reset the example
const resetBtn = document.querySelector(".reset");
resetBtn.addEventListener("click", () => window.location.reload(true));
```

Have a look at our [insertAdjacentElement.html](https://mdn.github.io/dom-examples/insert-adjacent/insertAdjacentElement.html)
demo on GitHub (see the [source code](https://github.com/mdn/dom-examples/blob/main/insert-adjacent/insertAdjacentElement.html) too.) Here, we have a sequence of {{htmlelement("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()`.
#### Result

{{embedlivesample("Inserting before and after", "", "200")}}

## Specifications

Expand Down