Home > Web Front-end > JS Tutorial > JavaScript method to create elements (code)

JavaScript method to create elements (code)

不言
Release: 2019-03-20 11:32:44
forward
2455 people have browsed it

The content this article brings to you is about the method (code) of creating elements in JavaScript. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1. Dynamically create element one document.write()

For example, output a li tag to the page

<pre class="html" name="code"><span style="font-size:12px;"><script>
  document.write("<li>123</li>");</script></span>
Copy after login

It will be inserted into the body tag, but this method is rarely used, because it will affect the layout of the page and even wash away the original content of the page, thus only displaying the output content

2. Dynamically create element 2, innerHTML

<span style="font-size:12px;"><body>
<div id="box"></div>
<script>
  var box = document.getElementById("box");
  box.innerHTML = "<p>这是p标签</p>";
</script>
</body></span>
Copy after login

, and a p tag will be inserted into the div tag, and "This is a tag" will be output on the page. This method is used when there are many tags to be added. .

3. Dynamically create element three document.createElement()

<span style="font-size:12px;"><body>
<div id="div"></div>
<script>
  var divobj = document.getElementById("div"); var li = document.createElement("li"); //创建一个li标签 li.innerHTML = "123"; //给li标签赋值
divobj.appendChild(li); //将创建好的li标签追加到box标签中 </script> </body></span>
Copy after login

A li tag will be created under the div tag. When a dynamically created tag is required This method is used rarely

This article has ended here. For more exciting content, you can pay attention to the JavaScript Tutorial Video column on the PHP Chinese website. !

The above is the detailed content of JavaScript method to create elements (code). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:cnblogs.com
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template