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.
A basic function: function myStuff(a,b,c){ var _c = _c || c || {}; console.log(_c); } The idea is to use a cached value if used before, or a new value if new/different. The question is: if ...
A basic function: function myStuff(a,b,c){ var _c = _c || c || {}; console.log(_c); } The idea is to use a cached value if used before, or a new value if new/different. The question is: if ...
Can phantomjs perform actions like getText() or enterText() inside iFrame? I am using protractor to do my testing. Phantomjs can perform actions in the default frame but inside iframe the locators get ...
Can phantomjs perform actions like getText() or enterText() inside iFrame? I am using protractor to do my testing. Phantomjs can perform actions in the default frame but inside iframe the locators get ...
I have this JQuery script that is looking at some DIVs and getting the image sizes and setting the div size according to the images. I had a JQuery script to get all the DIVs and loop to each image ...
I have this JQuery script that is looking at some DIVs and getting the image sizes and setting the div size according to the images. I had a JQuery script to get all the DIVs and loop to each image ...
I am using: Grunt with the watch plugin for live reload & Sublime Text 2's SFTP plugin for uploading files on save Live reload is just a little quicker than the SFTP upload. Using Guard, you ...
I am using: Grunt with the watch plugin for live reload & Sublime Text 2's SFTP plugin for uploading files on save Live reload is just a little quicker than the SFTP upload. Using Guard, you ...