Home  >  Article  >  Web Front-end  >  JavaScript adds elements to the page

JavaScript adds elements to the page

醉折花枝作酒筹
醉折花枝作酒筹Original
2021-06-11 11:01:454271browse

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.

JavaScript adds elements to the page

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.

JavaScript adds elements to the page

JavaScript adds elements to the page

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn