Home > Web Front-end > JS Tutorial > body text

Implementation method of dynamic creation of javascript elements_javascript skills

WBOY
Release: 2016-05-16 15:59:25
Original
1005 people have browsed it

The example in this article describes the implementation method of dynamic creation of javascript elements. Share it with everyone for your reference. The specific analysis is as follows:

document.write can only be created dynamically during page loading

You can call the document's createElement method to create a DOM object with the specified tag, and then add the
by calling the element's appendChild method. The newly created element is added under the corresponding element

For example:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <title>Dom动态创建元素</title>
 <script type="text/javascript">
 function CreateButton() {
  var div = document.getElementById("divMain");
  var myButton = document.createElement("input");
  myButton.type = "button";
  myButton.value = "我是动态添加的";
  //myButton.id="btn"; 注意:如果设置id的话要避免重复
  div.appendChild(myButton); //添加到div上
 }
 </script>
</head>
<body>
 <div id="divMain"></div>
 <input type="button" value="添加元素" onclick="CreateButton()" />
</body>
</html>
Copy after login

I hope this article will be helpful to everyone’s JavaScript programming design.

source:php.cn
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!