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.
Da zero ad eroe
Entra nel mondo della programmazione web: variabili, funzioni, array, DOM, eventi. Con esercizi pratici e progetti coinvolgenti.
⏱️8 ore di corso registrato
🧩Più di 50 algoritmi risolti passo passo
🎯Livello base — da zero ad eroe
💻100% online, fruibile quando vuoi
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.
📚 Consigliato per te
50 Algoritmi per imparare JavaScript
Una guida step by step per imparare JavaScript con esercizi svolti.
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.
Un'email ogni tanto con i nuovi articoli e le guide — niente spam, ti disiscrivi quando vuoi.
🍪 Questo sito usa i cookie
Utilizziamo cookie tecnici necessari al funzionamento e, previo tuo consenso, cookie
analitici e di terze parti per migliorare l'esperienza di navigazione.
Leggi la Cookie Policy e la
Privacy Policy.