Create node from html

Convert String to DOM Nodes

My original post featured DOMParser , a JavaScript API for converting HTML strings into DOM nodes. While DOMParser works well in most cases, that API does have some rough edges and isn’t as performant as another API: ContextualFragment . I’ve rewritten this post to highlight ContextualFragment , but if you still care to learn about DOMParser , please see the original text at the bottom of this post.

It wasn’t too long ago that browsers were mostly stagnant when it came to implementing new APIs and features, leading to the rise of MooTools (FTW), jQuery, Dojo Toolkit, Prototype, and likewise JavaScript toolkits. Then we started doing more client side rendering and were forced to use a variety of tricks to handle templates, including massive HTML strings in our JavaScript and even abusing tags to hold our templates.

Of course after you’ve placed your content into the template, you then need to turn that string into DOM nodes, and that process had a few of its own tricks, like creating an offscreen, dummy , setting its innerHTML to the string value, grabbing the firstChild , and moving the node to its desired node. Each JavaScript toolkit would use its own strategy for converting string to DOM, highlighting the need for a standard method to accomplish this task.

Today there’s a little known (but standard) way for converting string to DOM with JavaScript: ContextualFragment .

I’ve touched on DocumentFragment to create and store DOM nodes for performance in the past, but that post illustrated element creation via document.createElement :

// Use a DocumentFragment to store and then mass inject a list of DOM nodes var frag = document.createDocumentFragment(); for(var x = 0; x

To create DOM nodes from a string of HTML we’ll use document.createRange().createContextualFragment :

let frag = document.createRange().createContextualFragment('
One
Two
'); console.log(frag); /* #document-fragment
One
Two
*/

DocumentFragment objects share most of the methods that NodeList objects have, so you can use typical DOM methods like querySelector and querySelectorAll as well DOM traversal properties like firstChild with the resulting DocumentFragment :

let firstChild = frag.firstChild; let firstDiv = frag.querySelector('div'); let allDivs = frag.querySelectorAll('div');

When you’re ready to inject all of the created DOM nodes, you can simply execute:

// "placementNode" will be the parent of the nodes within the DocumentFragment placementNode.appendChild(frag);

You can also inject nodes one at a time:

placementNode.appendChild(frag.firstChild);

The document.createRange().createContextualFragment function is an awesome, sane method for converting strings to DOM nodes within JavaScript. Ditch your old shims and switch to this performant, simple API!

Читайте также:  Php domain name hosting

The Original Post: DOMParser

Today we have a standard way for converting string to DOM with JavaScript: DOMParser .

The JavaScript

All you need to do is create a DOMParser instance and use its parseFromString method:

let doc = new DOMParser().parseFromString('
Hello!
', 'text/html');

Returned is a document containing the nodes generated from your string. With said document you can use standard node traversal methods to retrieve the nodes we specified in our string:

let doc = new DOMParser().parseFromString('
Hello!
', 'text/html'); let div = doc.body.firstChild; let divs = doc.body.querySelectorAll('div');

You don’t need a single wrapping element like JSX components — you can have sibling elements:

let doc = new DOMParser().parseFromString('
1
2
', 'text/html'); let firstDiv = doc.body.firstChild; let secondDiv = firstDiv.nextSibling;

Here’s a simple wrapping function for DOMParser to retrieve the nodes:

let getNodes = str => new DOMParser().parseFromString(str, 'text/html').body.childNodes; let nodes = getNodes('
1
2
'); // [div, div]

The DOMParser object is an awesome, sane method for converting strings to DOM nodes within JavaScript. Ditch your old shims and switch to this efficient, simple API!

Источник

JavaScript HTML DOM Elements (Nodes)

To add a new element to the HTML DOM, you must create the element (element node) first, and then append it to an existing element.

Example

const para = document.createElement(«p»);
const node = document.createTextNode(«This is new.»);
para.appendChild(node);

const element = document.getElementById(«div1»);
element.appendChild(para);

Example Explained

This code creates a new

element:

To add text to the

element, you must create a text node first. This code creates a text node:

Then you must append the text node to the

element:

Finally you must append the new element to an existing element.

This code finds an existing element:

This code appends the new element to the existing element:

Creating new HTML Elements — insertBefore()

The appendChild() method in the previous example, appended the new element as the last child of the parent.

If you don’t want that you can use the insertBefore() method:

Example

const para = document.createElement(«p»);
const node = document.createTextNode(«This is new.»);
para.appendChild(node);

Читайте также:  Java проверить наличие символа

const element = document.getElementById(«div1»);
const child = document.getElementById(«p1»);
element.insertBefore(para, child);

Removing Existing HTML Elements

To remove an HTML element, use the remove() method:

Example

Example Explained

The HTML document contains a element with two child nodes (two

elements):

Find the element you want to remove:

Then execute the remove() method on that element:

The remove() method does not work in older browsers, see the example below on how to use removeChild() instead.

Removing a Child Node

For browsers that does not support the remove() method, you have to find the parent node to remove an element:

Example

Example Explained

This HTML document contains a element with two child nodes (two

elements):

Find the element with id=»div1″ :

Find the

element with id=»p1″ :

Remove the child from the parent:

Here is a common workaround: Find the child you want to remove, and use its parentNode property to find the parent:

Replacing HTML Elements

To replace an element to the HTML DOM, use the replaceChild() method:

Example

const para = document.createElement(«p»);
const node = document.createTextNode(«This is new.»);
para.appendChild(node);

const parent = document.getElementById(«div1»);
const child = document.getElementById(«p1»);
parent.replaceChild(para, child);

Источник

HTML DOM Document createElement()

document.createElement() is a DOM Level 1 (1998) feature.

It is fully supported in all browsers:

Chrome Edge Firefox Safari Opera IE
Yes Yes Yes Yes Yes 9-11

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Document: createElement() method

In an HTML document, the document.createElement() method creates the HTML element specified by tagName, or an HTMLUnknownElement if tagName isn’t recognized.

Syntax

createElement(tagName) createElement(tagName, options) 

Parameters

A string that specifies the type of element to be created. The nodeName of the created element is initialized with the value of tagName. Don’t use qualified names (like «html:a») with this method. When called on an HTML document, createElement() converts tagName to lower case before creating the element. In Firefox, Opera, and Chrome, createElement(null) works like createElement(«null») .

An object with the following properties:

The tag name of a custom element previously defined via customElements.define() . See Web component example for more details.

Return value

Note: A new HTMLElement is returned if the document is an HTMLDocument, which is the most common case. Otherwise a new Element is returned.

Examples

Basic example

This creates a new and inserts it before the element with the ID » div1 «.

HTML

doctype html> html lang="en-US"> head> meta charset="UTF-8" /> title>Working with elementstitle> head> body> div id="div1">The text above has been created dynamically.div> body> html> 

JavaScript

.body.onload = addElement; function addElement()  // create a new div element const newDiv = document.createElement("div"); // and give it some content const newContent = document.createTextNode("Hi there and greetings!"); // add the text node to the newly created div newDiv.appendChild(newContent); // add the newly created element and its content into the DOM const currentDiv = document.getElementById("div1"); document.body.insertBefore(newDiv, currentDiv); > 

Result

Web component example

The following example snippet is taken from our expanding-list-web-component example (see it live also). In this case, our custom element extends the HTMLUListElement , which represents the element.

// Create a class for the element class ExpandingList extends HTMLUListElement  constructor()  // Always call super first in constructor super(); // constructor definition left out for brevity // … > > // Define the new element customElements.define("expanding-list", ExpandingList,  extends: "ul" >); 

If we wanted to create an instance of this element programmatically, we’d use a call along the following lines:

let expandingList = document.createElement("ul",  is: "expanding-list" >); 

The new element will be given an is attribute whose value is the custom element’s tag name.

Note: For backwards compatibility with previous versions of the Custom Elements specification, some browsers will allow you to pass a string here instead of an object, where the string’s value is the custom element’s tag name.

Specifications

Browser compatibility

BCD tables only load in the browser

See also

  • Node.removeChild()
  • Node.replaceChild()
  • Node.appendChild()
  • Node.insertBefore()
  • Node.hasChildNodes()
  • document.createElementNS() — to explicitly specify the namespace URI for the element.

Found a content problem with this page?

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

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

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