Home > Article > Web Front-end > JavaScript adds elements to the page
Method: 1. Use "getElementsByTagName()" to get the parent node element; 2. Use "createElement()" to dynamically create tags; 3. Use "appendChild()" to place the tag under the specified element; 4. , use "innerHTML" to add text content.
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
If you want to add elements dynamically to the page, you must first determine which element to add the element after, and then use the appendChild method of js to append the element after the element.
1. Get the parent node element var body = document.getElementsByTagName('body')[0].
2. Then dynamically create a tag var a = document.createElement('a').
3. Append the created a tag to body.appendChild(a) below body.
4. Add text content a.innerHTML = 'This is a link' in the a tag. Add a link a.href = 'https://www.baidu.com/' to the a tag.
Extended information:
Some native methods of js
element.appendChild() method adds the last child node to the node.
element.innerHTML sets or returns the content of the element.
document.getElementsByTagName() returns a collection of objects with the specified tag name.
document.getElementById() returns a reference to the first object with the specified id.
document.createElement() creates an element by specifying a name.
[Recommended learning: javascript advanced tutorial]
The above is the detailed content of JavaScript adds elements to the page. For more information, please follow other related articles on the PHP Chinese website!