Last Updated : Jan 1, 2023
Putting together elements
To add new element to the end of a parent node, first, construct it with createElement and then appendChild() for the newly generated element.
The appendChild() method also works with existing child nodes, allowing you to relocate them throughout the document. AppendChild() transfers the supplied child node from its present place to the end of the list of child nodes under the specified parent node in this case.
It's worth noting that there's no need to delete existing child nodes from their parent node before appending them to another node.
This is due to the fact that a node cannot exist in two places within the same document at the same time.
When you use appendChild() to add an existing child node to another node, the child node is removed first, then inserted at the new location.
<html> <head> </head> <script> var myDiv = document.createElement("div"); myDiv.id = 'div_id'; myDiv.innerHTML = "<h1>Welcome!</h1>"; document.body.appendChild(myDiv); </script> </body> </html>
- To begin, type <! DOCTYPE html> to tell the web browser that the file is in HTML format.
- The <html> element, on the other hand, is used to signal the start of HTML content.
- The <head> tag now contains the information about web pages. The <title> element is used in this tag to provide a web page title. For example, the <head> and <title> tags are paired tags. As a result, both have the </head> and </title> closing tags.
- Using the document, we created a DIV element. createElement() is a method that creates a new element.
- We changed the ID property of the element to "div_id."
- We changed the DIV's content by using the innerHTML attribute.
- Finally, we used the appendChild() method to append the element to our body.
- The <body> and <html> tags are closed by the </body> and </html> tags, respectively.
Although this method is a little more time-consuming, it will work in all the use cases. Overall, it's a better option than altering the document.body.innerHTML property manually.