简体   繁体   中英

Create new element vs append html

this is a pure academic question. is it better practice to add new elements to the dom this way with create new element

<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>

<script>
var para = document.createElement("p");
var node = document.createTextNode("This is new.");
para.appendChild(node);
var element = document.getElementById("div1");
element.appendChild(para);
</script>

or by simply appending the html to the parent element like so

<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>

<script>
document.getElementById("div1").innerHTML += "<p>This is new</p>";
</script>

is it better practice to do one or the other or is it purely choice or something else entirely. Thank You

It depends on where the text originates. You don't want to create more XSS vulnerabilities. If you control the text, then parsing it as HTML (and CSS and JavaScript) is reasonable and easier to code. If you don't control the text, then make the element and set the attributes and text using the API. Then it won't become malicious code you didn't anticipate.


PS. I overlooked your use of the += operator on innerHTML. I wrote as though you were comparing replacement of the node's contents (ie innerHTML = ). See Quentin's answer for why += is much worse.

innerHTML += "<p>This is new</p>"; will:

  1. Convert the existing DOM to HTML source code
  2. Modify that HTML source code
  3. Convert that HTML source code to a new DOM
  4. Replace the old DOM with the new DOM

This is inefficient, will destroy any existing event handlers bound to the elements, will wipe out the values of form controls (since the value attribute , which will be serialised to HTML, holds the default, not current, value), and may have other side effects I haven't thought of.

In general, DOM manipulation has fewer surprises and is easier to debug.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM