Currently, am I learning about API and how to use them with dynamic websites. I've coded some sample Websites, where I get my data from an API.
I've been using innerHTML
to add the content to my page.
My teacher used createElement
textContent
and appendChild
to add the content to his page during classes.
When asked, he explained that innerHTML is much more unsecure as textContent, as e.g. if the API is unreliable or has been injected with an malicious code, innerHTML can edit the whole HTML, as instead of just the Content with textContent. So did ChaseMoskal try to explain in this comment innerText vs innerHtml vs label vs text vs textContent vs outerText
I get the basic idea, however, explaining with following code example, I feel that both present the same security issues.
var container = document.querySelector("#container");
var json1 = "Link to an image of my house";
var json2 = "Link to an image of my boat";
var jsonMaliciousCode = "maliciousCode3000"
// Create p element with innerHTML
container.innerHTML += "<a href=\""+maliciousCode+"\">" + json1 + "</a>";
// Create p element with textContent, href and appendChild
var innerExample = document.createElement('a');
innerExample.textContent = json2;
innerExample.href = maliciousCode;
container.appendChild(innerExample);
Working example: https://jsfiddle.net/vh8hLhbj/4/
What is it that I don't get or am missing out?