Inserting HTML elements with JavaScript

2019-01-03 22:04发布

Instead of tediously search for workarounds for each type of attribute and event when using the following syntax:

   elem = document.createElement("div");
   elem.id = 'myID';
   elem.innerHTML = ' my Text '
   document.body.insertBefore(elem,document.body.childNodes[0]);

Is there a way where I can just declare the entire HTML element as a string? like:

  elem = document.createElement("<div id='myID'> my Text </div>");
  document.body.insertBefore(elem,document.body.childNodes[0]);

7条回答
神经病院院长
2楼-- · 2019-01-03 23:04

You want this

document.body.insertAdjacentHTML( 'afterbegin', '<div id="myID">...</div>' );
查看更多
登录 后发表回答