Javascript create use element

JavaScript CreateElement

Summary: in this tutorial, you will learn how to use the JavaScript document.createElement() to create a new HTML element and attach it to the DOM tree.

To create an HTML element, you use the document.createElement() method:

let element = document.createElement(htmlTag);Code language: JavaScript (javascript)

The document.createElement() accepts an HTML tag name and returns a new Node with the Element type.

1) Creating a new div example

Suppose that you have the following HTML document:

html> html> head> meta charset="utf-8"> title>JS CreateElement Demo title> head> body> body> html>Code language: HTML, XML (xml)

The following example uses the document.createElement() to create a new element:

let div = document.createElement('div');Code language: JavaScript (javascript)

And add an HTML snippet to the div :

div.innerHTML = 'p>CreateElement example p>';Code language: HTML, XML (xml)

To attach the div to the document, you use the appendChild() method:

document.body.appendChild(div);Code language: CSS (css)
html> html> head> meta charset="utf-8"> title>JS CreateElement Demo title> head> body> script> let div = document.createElement('div'); div.id = 'content'; div.innerHTML = '

CreateElement example

'
; document.body.appendChild(div);
script> body> html>
Code language: HTML, XML (xml)

Adding an id to the div

If you want to add an id to a div , you set the id attribute of the element to a value, like this:

let div = document.createElement('div'); div.id = 'content'; div.innerHTML = '

CreateElement example

'
; document.body.appendChild(div);
Code language: JavaScript (javascript)

Adding a class to the div

The following example set the CSS class of a new div note :

let div = document.createElement('div'); div.id = 'content'; div.className = 'note'; div.innerHTML = '

CreateElement example

'
; document.body.appendChild(div);
Code language: JavaScript (javascript)

Adding text to a div

To add a piece of text to a , you can use the innerHTML property as the above example, or create a new Text node and append it to the div :

// create a new div and set its attributes let div = document.createElement('div'); div.id = 'content'; div.className = 'note'; // create a new text node and add it to the div let text = document.createTextNode('CreateElement example'); div.appendChild(text); // add div to the document document.body.appendChild(div);Code language: JavaScript (javascript)

Adding an element to a div

To add an element to a div , you create an element and append it to the div using the appendChild() method:

let div = document.createElement('div'); div.id = 'content'; div.className = 'note'; // create a new heading and add it to the div let h2 = document.createElement('h2'); h2.textContent = 'Add h2 element to the div'; div.appendChild(h2); // add div to the document document.body.appendChild(div); Code language: JavaScript (javascript)

2) Creating new list items ( li ) example

Let’s say you have a list of items:

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

The following code adds two li elements to the ul :

let li = document.createElement('li'); li.textContent = 'Products'; menu.appendChild(li); li = document.createElement('li'); li.textContent = 'About Us'; // select the ul menu element const menu = document.querySelector('#menu'); menu.appendChild(li); Code language: JavaScript (javascript)
ul id="menu"> li>Home li> li>Products li> li>About Us li> ul>Code language: HTML, XML (xml)

3) Creating a script element example

Sometimes, you may want to load a JavaScript file dynamically. To do this, you can use the document.createElement() to create the script element and add it to the document.

Читайте также:  Символы новой строки html

The following example illustrates how to create a new script element and loads the /lib.js file to the document:

let script = document.createElement('script'); script.src = '/lib.js'; document.body.appendChild(script);Code language: JavaScript (javascript)

You can first create a new helper function that loads a JavaScript file from an URL:

function loadJS(url) < let script = document.createElement('script'); script.src = url; document.body.appendChild(script); >Code language: JavaScript (javascript)

And then use the helper function to load the /lib.js file:

loadJS('/lib.js');Code language: JavaScript (javascript)

To load a JavaScript file asynchronously, you set the async attribute of the script element to true :

function loadJSAsync(url) < let script = document.createElement('script'); script.src = url; script.async = true; document.body.appendChild(script); >Code language: JavaScript (javascript)

Summary

  • The document.createElement() creates a new HTML element.
  • The element.appendChild() appends an HTML element to an existing element.

Источник

Learn How JavaScript Create Element

In this tutorial, you will learn how JavaScript create element with classes and id. You will see how to append these newly created elements at the desired location on the webpage.

One of the most commonly used tasks in web development is to create elements dynamically . This is done by using JavaScript to make websites interactive to the users.

A simple example you can see in a to do list app where you can add, delete and edit to do list items. These list items are created dynamically using JavaScript.

A webpage is interactive when the user is actively engaged with the contents, elements, and functionality of the webpage.

javascript create element

Let’s see how you can create an HTML element using javascript and append it anywhere within the webpage.

Читайте также:  Таблица

Table of content — JavaScript Create Element

Create Element JavaScript

To create an HTML element using JavaScript use the document.createElement() method.

To create an element you need to pass the element name as an argument to the method.

The document.createElement() method creates the element with the given name and returns it as a Node object.

document.createElement("TagName");

The TagName argument is the name of the element you want to create.

  • To create a element pass div , DIV , Div , DiV , etc.
  • To create a

    element pass p or P .

  • To create a element pass img , IMG , Img , IMg , etc.

Note : The createElement method converts the element name to lowercase and then creates the element. So if you pass DIV as an argument, it will create a div element.

The method also returns the reference to the newly created element which you can store to be used later.

let element = document.createElement("P");

Now your element is created and the reference of the element is stored in a variable.

But, this newly created element is floating aimlessly in the document, you have to stitch it to somewhere in the body to be seen or used.

append element in javascript

Append Newly Created Element

Just creating an element is not enough to show it on the webpage. You have to append it to somewhere in the body.

The newly created element has no role in the document and is not visible to the user because it is not part of the DOM yet.

There are 3 methods to append an element to the webpage:

1. append() Method

The append() method appends the element to the end of the parent element.

The method is called upon the parent element and takes the child element as an argument and appends it as the last child of the parent element.

For example in the given example, the is parent element and the

is the child element. If you add another

element, it will be appended as the last child of the element.

let element = document.createElement("P"); element.innerHTML = "Paragraph 3"; // Append the element to the parent element document.getElementById("parent").append(element);

The final look of the DOM after the above code is:

Paragraph 1

Paragraph 2

Paragraph 3

2. appendChild() Method

The appendChild() method is the same as the append() method it appends the element to the end of the parent element.

Although there are few differences between the append() and appendChild() methods:

append() appendChild()
Using the append() method you can append both DOMString and DOMNodes (element) to the parent element. Using the appendChild() method you can append only DOMNodes (element) to the parent element.
The append() method returns the appended node. The appendChild() method returns nothing.
The append() method can append multiple elements at once. The appendChild() method can only append one element at a time.

Here is an example using the appendChild() method:

// selecting parent element var parent = document.getElementById('parent'); var child = document.createElement('p'); child.innerHTML = 'Paragraph 3'; parent.appendChild(child);

3. insertBefore() Method

The insertBefore() method inserts the element before the reference element and makes it the previous sibling of the reference element.

The method is called upon the parent element and operations of inserting the element are performed on its child nodes.

If the node already exists in the parent element, it will be moved to the new position.

// selecting parent var parent = document.getElementById('parent'); // selecting sibling element var sibling = document.getElementById('para1'); var element = document.createElement('p'); element.innerHTML = 'Paragraph 3'; parent.insertBefore(element, sibling);

Here is how DOM looks before and after appending a new element.

append element to parent element

Javascript Create Element with Class

To create an element with a class, you need to add the class attribute to the element after creating it.

To add a class to an element, you can use the classList.add() method on the element.

Learn more ways of how Javascript add class to an element.

var parentElement = document.body; // creating new element var element = document.createElement("P"); element.innerHTML = "New paragraph with 'box' class."; // adding class to the element element.classList.add("box"); parentElement.appendChild(element);

Javascript Create element with id

The id property of an element is used to get and set the id of an element.

To create an element with an id use createElement to create an element and assign an id to element.id .

In the example below whenever the button is clicked it create an element and add a unique id to it.

 

Javascript Create element with attributes

HTML elements can have attributes. Attributes are used to add extra information to an element.

To add an attribute to an element, you can use the setAttribute() method on the element.

Elements like and have some compulsory attributes like type and src .

To add an attribute to an element, use the setAttribute() method on the element and pass the attribute name and value as arguments.

Here is an example that creates an image element and adds a few attributes to it.

let parentElement = document.body; // creating new element let element = document.createElement("IMG"); // adding attributes to the element element.setAttribute("src", "https://i.imgur.com/Rnj7kZj.jpeg"); element.setAttribute("alt", "picture of pluto"); element.setAttribute("title", "picture of pluto"); parentElement.appendChild(element);

Conclusion

You have seen how Javascript create element. Here is a quick summary:

  1. Create element using document.createElement() method.
  2. Add class to an element using element.classList.add() method.
  3. Add id to an element using element.id = «id» + count; .
  4. Add attribute to an element using element.setAttribute() method.
  5. Append element to parent element using append() , appendChild() , or insertBefore() method.

Источник

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