Javascript tips for generating HTML elements

  • 2020-03-30 03:00:45
  • OfStack

There are two ways that Javascript can generate HTML elements. The first is the more formal way of creating elements, and the second is to write out HTML elements directly using the write() method in Javascript.

Method one:


   //CreateElement () creates the input element into the obj object
   var obj = document.createElement('input');
   //Select the previous element of the place to generate
   var before = document.getElementById('before');
   //Set the obj element name, value
      obj.name='name';
      obj.value='value';
      //SetAttribute is free to define attributes, not only the id and type, but also the name and value
      obj.setAttribute('id','idname');
      obj.setAttribute('type','typename');
      //Add obj after the previous element
      before.appendChild(obj);

Method 2:


document.write("<inpt name='name' value='value' id='idname' type='typename'>");

Here are two html-generating < Input> Element method, the first is more standard, more code, the second is less code.


Related articles: