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>
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>
, 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>
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!