- Dynamically creating HTML elements using Javascript?
- 6 Answers 6
- How to add a new element to HTML DOM in JavaScript?
- Example 1
- Example 2
- JavaScript HTML DOM
- Example 3
- JavaScript HTML DOM
- JavaScript HTML DOM Elements (Nodes)
- Example
- Example Explained
- Creating new HTML Elements - insertBefore()
- Example
- Removing Existing HTML Elements
- Example
- Example Explained
- Removing a Child Node
- Example
- Example Explained
- Replacing HTML Elements
- Example
- Document: createElement() method
- Syntax
- Parameters
- Return value
- Examples
- Basic example
- HTML
- JavaScript
- Result
- Web component example
- Specifications
- Browser compatibility
- See also
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
Dynamically creating HTML elements using Javascript?
I want to dynamically create some HTML elements (3 html element) and then return this html code as a string in a variable. I don’t want to write the HTML code in the following function to some div, but, I want to return it in a var.
function createMyElements(id1,id2,id3) < //create anchor with id1 //create div with id 2 //create xyz with id3 //now return the html code of above created just now >
html code of elemets in a var and finally i will do document.getElementbyID(«yu»).innerHTML = var_containing_code
6 Answers 6
[Edit 2021/10] This answer is now > 10 years old. Here is a snippet containing several ways to create and/or inject elements. The answer for the question asked (create some element(s) and retrieve their html code) can be found @ the bottom of the snippet.// The classic createElement // ------------------------- // create a paragraph element using document.createElement const elem = document.createElement(`p`); elem.id = `myBrandnewDiv1`; // put in some text elem.appendChild(document.createTextNode(`My brand new div #1`)); // append some html (for demo, preferrably don't use innerHTML) elem.innerHTML += ` => created using
(see ">MDN)`>) ); document.querySelector(`#myBrandnewDiv2`).appendChild(fragment); // Create, but don't inject // ------------------------ const virtual = Object.assign( document.createElement(`p`), < innerHTML: ` id1document.createElement
`; // append a new paragraph within #myBrandNewDiv1 const nested = elem.appendChild(document.createElement(`p`)); nested.classList.add(`nested`); // add some text to that nested.textContent = `I am nested!`; // the elements are still in memory, now add the // whole enchillada to the document document.body.appendChild(elem); // insertAdjacentHTML // ------------------ // nest an element within the nested div nested.insertAdjacentHTML(`afterbegin`, `This text will appear above the text of my parent, that being div#nested. Someone had the nerve to insert me using`); // Object.assign // ------------- // Use Object.assign to create an element and // assign properties/html to it in one go const newElem = Object.assign( document.createElement(`div`), < id: `myBrandnewDiv2`, innerHTML: `div#myBrandnewDiv2 signing in. I was assigned usinginsertAdjacentHTML
Object.assign
…`>); document.body.appendChild(newElem); // insertAdjacentElement combined with Object.assign // ------------------------------------------------- // use the above technique combined with insertAdjacentElement newElem.insertAdjacentElement( `beforeend`, Object.assign(document.createElement(`span`), < id: `myBrandnewnested2_nested`, innerHTML: `
Me too! And appended I was withinsertAdjacentElement
` >) ); // createDocumentFragment // ---------------------- // Use a document fragment to create/inject html const fragment = document.createDocumentFragment(); const mdnLnk = `https://developer.mozilla.org/en-US/` + `docs/Web/API/Document/createDocumentFragment`; fragment.appendChild( Object.assign( document.createElement(`p`), createDocumentFragmentHi!Hi 2!
`, classList: [`xyz`], > ); const prepareHtml4Reporting = html => html.replace(/html only$ `);I have used some of these methods in this library (see /src/DOM.js ), with a mechanism for sanitizing html before it is injecting.
How to add a new element to HTML DOM in JavaScript?
Step 1 − To insert an element into HTML DOM, firstly, we need to create an element and append to HTML DOM. The document.createElement() is used to create the HTML element. The syntax to create an element is shown below.
document.createElement(tagName[, options]);
- tagName is the name of the tag to be created. The tag is of
type.
- options param is an optional element object.
Step 2 − After creation of a tag, we need to create a text to assign to the tag. The syntax to create a text node is shown below.
Document.createTextNode(“String”);
Step 3 − After creating the text, we need to add the text to the element
type and thus finally adding to the div tag. The syntax to append the element to a tag is shown below.
Example 1
In the following example, initially the div section consists of only 2 texts. But later on, one more text is created and added to the div section as shown in the output.
Tutorix
Tutorialspoint
On executing the above code, the following output is generated.
Example 2
The following is an example program on how to add an element to HTML DOM.
JavaScript HTML DOM
How to add a new element to HTML DOM
Introduction.
Conclusion.
On executing the above code, the following output is generated.
Example 3
The following is an example program on how to add an element to HTML DOM. Here, the insertBefore method is used instead of append method to add the element to the div tag.
JavaScript HTML DOM
How to add a new element to HTML DOM
Introduction.
Conclusion.
On executing the above code, the following output is generated.
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);
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);
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.