We continue our tutorial in JavaScript using the createTextNode method, which is the method that allows us to insert text into a node.
In fact, after having created a new element or on an already existing element, it may be necessary to insert some text inside it.
To do this, you can use, for example, the JavaScript createTextNode() method, where inside the round brackets I specify the new text to be inserted.
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 of this method is as follows: element.createTextNote().
createTextNode JavaScript – example
In this example we will create a new paragraph, where we will insert any text inside. The new paragraph will be created when the button is clicked.
Try it out by clicking on the button below, you can click it also several times.
Development
We explain in detail the procedure for making this example.
In the HTML code we insert a 'Add new paragraph' button as before and under it we add a level (div), where the new generated paragraph will appear.
Our add () function will carry out very simple instructions:
will first create the new paragraph element,
then it will write some text within this paragraph using the createTextNode method of JavaScript
and then using the appendChild () method will add this newly created content to the desired location. The desired point is obtained thanks to the getElementById method.
So, here is the html code to create the example:
📚 Consigliato per te
50 Algoritmi per imparare JavaScript
Una guida step by step per imparare JavaScript con esercizi svolti.
<button onclick="add()">Add a new paragraph</button>
<div id="text"></div>
And JavaScript code to create the example:
function add() {
var paragraph = document.createElement("p");
var text = document.createTextNode("Coding Creativo");
paragraph.appendChild(text);
document.getElementById("text").appendChild(paragraph);
}
Conclusion
So, summarizing in this lesson we learned how to create elements in the DOM with JavaScript and how to use the createElement(), createTextNode() and appendChild() methods.
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.