Reputation: 143
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
Upvotes: 2
Views: 736
Reputation: 12214
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.
Upvotes: 3
Reputation: 943510
innerHTML += "<p>This is new</p>";
will:
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.
Upvotes: 2