To add a new element to the HTML DOM, we have to create it first and then we need to append it to the existing element. Show Steps to follow1) First, create a div section and add some text to it using <p> tags. 2) Create an element <p> using document.createElement("p"). 3) Create a text, using document.createTextNode(), so as to insert it in the above-created element("p"). 4) Using appendChild() try to append the created element, along with text, to the existing div tag. Thus a new element is created(<p>) and appended to the existing element(<div>). ExampleIn the following example, initially the div section consists of only 2 texts. But later on, one more text is created and added to the div section as shown in the output. Live Demo <html> <body> <div id="new"> <p id="p1">Tutorix</p> <p id="p2">Tutorialspoint</p> </div> <script> var tag = document.createElement("p"); var text = document.createTextNode("Tutorix is the best e-learning platform"); tag.appendChild(text); var element = document.getElementById("new"); element.appendChild(tag); </script> </body> </html> OutputTutorix Tutorialspoint Tutorix is the best e-learning platform
Updated on 30-Jul-2019 22:30:26
The Differences from
Syntax
Parameters
A set of Return valueExceptions
Thrown when the node cannot be inserted at the specified point in the hierarchy. ExamplesAppending an element
Appending text
Appending an element and text
The append method is unscopable The
Specifications
Browser compatibilityBCD tables only load in the browser See alsoHow do you append text in JavaScript?To append text to an element:. Use the document. createTextNode() method to create a text node.. Use the appendChild() method to append the text node to the element.. The appendChild method will add the text node to the end of the element's list of children.. How do you add an element to a div?Steps to follow. First, create a div section and add some text to it using <p> tags.. Create an element <p> using document. createElement("p").. Create a text, using document. ... . Using appendChild() try to append the created element, along with text, to the existing div tag.. How do I change the content of a div?Use the textContent property to change the text of a div element, e.g. div. textContent = 'Replacement text' . The textContent property will set the text of the div to the provided string, replacing any of the existing content.
Can I use innerHTML?Here's when to use innerHTML or appendChild: Use innerHTML when you're setting text inside of an HTML tag like an anchor tag, paragraph tag, span, div, or textarea. Use appendChild() If you're trying to add new DOM elements inside of another DOM element.
|