The method of adding elements in javascript
This article focuses on "how to add elements in javascript". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to add elements in javascript.
Method: 1, the appendChild () method inserts the new element at the end, the syntax "appendChild (newchild)"; 2, the insertBefore () method, inserts the new element at the beginning, the new syntax "insertBefore (newchild,refchild)".
There are two ways to insert a new node (element) in a document, one at the beginning and one at the end.
AppendChild () method: inserts a new node at the end
The JavaScript appendChild () method adds a new child node to the end of the list of child nodes of the current node. The usage is as follows:
AppendChild (newchild)
The parameter newchild represents the newly added node object and returns the newly added node.
Example 1
Click the button to create and add a p tag
Click function myFunction () {var newItem=document.createElement ("LI") var textnode=document.createTextNode ("Water") newItem.appendChild (textnode) var list=document.getElementById ("myList") list.insertBefore (newItem,list.childNodes [0]);}}
Effect picture:
At this point, I believe you have a deeper understanding of "the method of adding elements in javascript". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!