Javascript add html after

JavaScript insertAfter

Summary: in this tutorial, you will learn how to insert a new node after an existing node as a child node of a parent node.

This tutorial was written when DOM API did not support the after() method. Now, you can use the after() method to insert a node after an element.

JavaScript DOM provides the insertBefore() method that allows you to insert a new node after an existing node as a child node.

To insert a new node after an existing node as a child node, you can use the following approach:

  • First, select the next sibling node of the existing node.
  • Then, select the parent node of the existing node and call the insertBefore() method on the parent node to insert a new node before that immediate sibling node.

The following insertAfter() function illustrates the logic:

function insertAfter(newNode, existingNode) Code language: JavaScript (javascript)

Suppose that you have the following list of items:

ul id="menu"> li>Home li> li>About li> li>Contact li> ul>Code language: HTML, XML (xml)

The following inserts a new node after the last list item:

let menu = document.getElementById('menu'); // create a new li node let li = document.createElement('li'); li.textContent = 'Services'; // insert a new node after the last list item insertAfter(li, menu.lastElementChild);Code language: JavaScript (javascript)
  • First, select the ul element by its id ( menu ) using the getElementById() method.
  • Second, create a new list item using the createElement() method.
  • Third, use the insertAfter () method to insert a list item element after the last list item element.
html> html> head> meta charset="utf-8"> title>JavaScript insertAfter() Demo title> head> body> ul id="menu"> li>Home li> li>About li> li>Contact li> ul> script> function insertAfter(newNode, existingNode) < existingNode.parentNode.insertBefore(newNode, existingNode.nextSibling); >let menu = document.getElementById('menu'); // create a new li node let li = document.createElement('li'); li.textContent = 'Services'; insertAfter(li, menu.lastElementChild); script> body> html>Code language: HTML, XML (xml)

The menu looks like the following after the insert:

ul id="menu"> li>Home li> li>About li> li>Contact li> li>Services li> ul>Code language: HTML, XML (xml)

Summary

  • JavaScript DOM hasn’t supported the insertAfter() method yet.
  • Use the insertBefore() method and the nextSibling property to insert a new before an existing node as a child of a parent node.
Читайте также:  Java add method to object

Источник

Element: after() method

The Element.after() method inserts a set of Node or string objects in the children list of the Element ‘s parent, just after the Element . String objects are inserted as equivalent Text nodes.

Syntax

after(node1) after(node1, node2) after(node1, node2, /* … ,*/ nodeN) 

Parameters

A set of Node or string objects to insert.

Return value

Exceptions

Thrown when the node cannot be inserted at the specified point in the hierarchy.

Examples

Inserting an element

let container = document.createElement("div"); let p = document.createElement("p"); container.appendChild(p); let span = document.createElement("span"); p.after(span); console.log(container.outerHTML); // " " 

Inserting text

let container = document.createElement("div"); let p = document.createElement("p"); container.appendChild(p); p.after("Text"); console.log(container.outerHTML); // " 
Text
"

Inserting an element and text

let container = document.createElement("div"); let p = document.createElement("p"); container.appendChild(p); let span = document.createElement("span"); p.after(span, "Text"); console.log(container.outerHTML); // " 
Text
"

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Apr 7, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

Insert an element after another DOM element with JavaScript

In earlier articles, we looked at how to create and element and insert it before another HTML element in the DOM using vanilla JavaScript.

In this article, you’ll learn different ways to insert an element after another one in the DOM with JavaScript.

The insertBefore() method, which we learned earlier to add an element before, can also be used to insert an HTML element after an HTML node. For this purpose, we need to use the element’s nextSibling property that returns a reference to the next node at the same tree level.

// create a new element const elem = document.createElement('p') // add text elem.innerText = 'I am a software engineer.' // grab target element reference const target = document.querySelector('#intro') // insert the element after target element target.parentNode.insertBefore(elem, target.nextSibling) 

The insertBefore() method works in all modern and old browsers, including Internet Explorer 6 and higher.

If you want to insert an HTML string after a certain element in the DOM, use the insertAdjacentHTML() instead, like below:

// insert HTML string after target element target.insertAdjacentHTML('afterend', '

I am a software engineer.

'
)

The insertAdjacentHTML() method automatically parses the given string as HTML and inserts the resulting elements into the DOM tree at the given position. Read this guide to learn more about it.

ES6 introduced a new method called after() to insert an element right after an existing node in the DOM. Just call this method on the element you want to insert an element after, and pass the new element as an argument:

// insert the element after the target element target.after(elem) 

The after() method only works in modern browsers, specifically Chrome, Safari, Firefox, and Opera. At the moment, Internet Explorer doesn’t support this method. However, you can use a polyfill to bring the support up to IE 9 and higher. Read Next: How to insert an element to the DOM in JavaScript ✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like.

Источник

JavaScript after()

Summary: in this tutorial, you’ll learn how to use the JavaScript after() method to insert a node after an element.

Introduction to the JavaScript after() method

The after() is a method of the Element type. The element.after() method allows you to insert one or more nodes after the element .

Here’s the syntax of the after() method:

Element.after(node)Code language: JavaScript (javascript)

In this syntax, the after() method inserts the node after the Element in the DOM tree.

For example, suppose you have a element and you want to insert a

element after it, you can use the after() method like this:

h1.after(p)Code language: JavaScript (javascript)

To insert multiple nodes after an element, you pass the nodes to the after() method as follows:

Element.after(node1, node2, . nodeN)Code language: JavaScript (javascript)

The after() method also accepts one or more strings. In this case, the after() method treats the strings as Text nodes:

Element.after(str1, str2, . strN)Code language: JavaScript (javascript)

The after() method returns undefined . If a node cannot be inserted, it’ll throw a HierarchyRequestError exception.

JavaScript after() examples

Let’s take some examples of using the JavaScript after() method.

1) Using JavaScript after() to insert a node after an element

The following example uses the after() method to insert a paragraph after a element:

html> html lang="en"> head> meta charset="UTF-8"> meta name="viewport" content="width=device-width, initial-scale=1.0"> title>JavaScript DOM - after() title> head> body> h1>JavaScript DOM - after() h1> script> const h1 = document.querySelector('h1'); // create a new paragraph element const p = document.createElement('p'); p.innerText = 'This is JavaScript DOM after() method demo'; // insert the paragraph after the heading h1.after(p); script> body> html>Code language: HTML, XML (xml)

First, get the heading element using the querySelector() method:

 const h1 = document.querySelector('h1');Code language: JavaScript (javascript)

Second, create a new paragraph element and set its innerText :

const p = document.createElement('p'); p.innerText = 'This is JavaScript DOM after() method demo';Code language: JavaScript (javascript)

Third, insert the

element after the element:

h1.after(p);Code language: JavaScript (javascript)

2) Using JavaScript after() to insert multiple nodes after an element

The following example uses the after() method to insert multiple nodes after an element:

html> html lang="en"> head> meta charset="UTF-8"> meta name="viewport" content="width=device-width, initial-scale=1.0"> title>JavaScript DOM - after() title> head> body> ul> li>Angular li> li>Vue li> ul> script> const list = document.querySelector('ul'); const libs = ['React', 'Meteor', 'Polymer']; const items = libs.map((lib) => < const item = document.createElement('li'); item.innerText = lib; return item; >); list.lastChild.after(. items); script> body> html>Code language: HTML, XML (xml)

First, select the ul element using the querySelector() method:

 const list = document.querySelector('ul');Code language: JavaScript (javascript)

Second, define an array of strings. In practice, you may get it from an API call.

 const libs = ['React', 'Meteor', 'Polymer'];Code language: JavaScript (javascript)

Third, transform the array of strings into an array of li elements using the map() method:

const items = libs.map((lib) => < const item = document.createElement('li'); item.innerText = lib; return item; >);Code language: JavaScript (javascript)

Finally, insert the list item elements after the last child of the ul element:

list.lastChild.after(. items);Code language: JavaScript (javascript)

Note that the . items uses the spread operator to spread out the element of the items array.

The ul element will look like the following:

ul> li>Angular li> li>Vue li> li>React li> li>Meteor li> li>Polymer li> ul>Code language: HTML, XML (xml)

3) Using JavaScript after() to insert strings

When you use strings in the after() method, it will treat them as Text nodes. For example:

html> html lang="en"> head> meta charset="UTF-8"> meta name="viewport" content="width=device-width, initial-scale=1.0"> title>JavaScript DOM - after() title> style> button < padding: 0.75em 1em; background-color: #F7DF1E; color: #000; cursor: pointer; border-radius: 50vw; > style> head> body> button>Donate Here button> script> const button = document.querySelector('button'); button.firstChild.after(' 🧡'); script> body> html>Code language: HTML, XML (xml)

Summary

Источник

Оцените статью