libri-javascript-python

In this lesson we study JavaScript createElement method, useful to create new elements in the DOM.

In the previous article we saw how to manipulate the DOM in JavaScript and studied methods for selecting elements on a page. You can consult the article at the following link: https://www.codingcreativo.it/en/javascript-dom/.

JavaScript createElement – How to create elements in the DOM

The element to create can be, for example, a new level, a new paragraph, a new title, etc.

To create elements in the DOM in JavaScript we will use the createElement() method, specifying the type of element you want to create inside the brackets.

The syntax is therefore this:

element = document.createElement(tag);

where tag can be any tag.

To add the new element, at the end of the list of elements contained in the current node, we use the appendChild() method.

JavaScript createElement – first example

So let’s see a practical example of how to create elements in the DOM with JavaScript.

If you try clicking the button below, a new item will appear.

In this point I insert the button:

For the development of this example, we first create a new layer (div) with id equal to button, which corresponds to the point where the new button will appear.

Here I will insert the button:

<div id="button">In this point I insert the button: </div>

Below we insert the button to which the onclick event is associated which calls the insert() function.

<input type="submit" onclick="insert()" value="insert">

We then create the insert() function in JavaScript.

This function will create a new button, with JavaScript createElement method, which will contain the word Scratch. Then we insert the element, using the appendChild () method, into the layer with the same id as the button.

So here’s the JavaScript code:



function insert() {
  var btn = document.createElement("button");
  btn.innerHTML = "scratch";
  document.getElementById("pulsante").appendChild(btn);
}

Conclusion

In this tutorial we have introduced the createElement JavaScript method, in the next lessons we will study other methods to manipulate the DOM.

Some useful links

JavaScript tutorial

JavaScript Calculator

Object in JavaScript

For in loop

Caesar cipher decoder

Slot Machine in JavaScript

Introduction to JavaScript language

Learn JavaScript – basic concepts