Two ways to create createElement in javascript

  • 2020-06-12 08:32:45
  • OfStack

This article illustrates two ways to create createElement in javascript. Share to everybody for everybody reference. Specific implementation methods are as follows:


<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <title>CreateElement Two ways to create it </title>
 <script type="text/javascript">
 function CreateButton1() {
  var btn = document.createElement("input");
  btn.type = "button";
  btn.value = " I created it dynamically 1";
  btn.onclick = function () {
  alert(this.value);
  }
  document.body.appendChild(btn);
 }
 function CreateButton2() {
  var btn = document.createElement("<input type='button' value=' I created it dynamically 2' "+"onclick='OnClick2(this)' />");
  document.body.appendChild(btn);
 }
 function OnClick2(btn) {
  alert(btn.value);
 }
 function CreateLink() {
  var link = document.createElement("<a href='http://www.baidu.com'> baidu </a>");
  // Note that the text "Baidu" is not displayed here, 
  // You must set up innerText or innerHTML
  link.innerText = " baidu ";
  document.body.appendChild(link);
 }
 function CreateLabel() {
  var lbl = document.createElement("label");
  lbl.setAttribute("for", "userName");
  lbl.setAttribute("myAge", "12");
  // Custom flags can be set 
  lbl.innerText = " The user name :";
  document.body.appendChild(lbl);
 }
 </script>
</head>
<body>
 <input type="button" value=" Dynamic create button 1" onclick="CreateButton1()" />
 <input type="button" value=" Dynamic create button 2" onclick="CreateButton2()" />
 <input type="button" value=" Dynamically creating links " onclick="CreateLink()" />
 <input type="button" value=" Dynamically create Label" onclick="CreateLabel()" />
 <input type="text" id="userName" value=" Li mo " />
</body>
</html>

Hopefully, this article has been helpful in your javascript programming.


Related articles: