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.
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:
<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.
Some useful links
Introduction to JavaScript language
Learn JavaScript – basic concepts