I am currently studying Javascript (and AJAX) for Web Development and found out I can either use textContent or appendChild(newlyCreatedTextNode) to add text to an element node. The question is: what is the difference between modifying the textContent of an Element Node and creating a new Text Node and then appending it to the Element Node?
(xhr is an XMLHttpRequest object)
Here is how I was doing the code:
xhr.onload = function() {
if (this.status === 200) {
// companies is an array of objects
let companies = JSON.parse(this.responseText);
// retailCompanies is an array of objects
let retailCompanies = companies.filter(company => company.category === "Retail");
// h1 with textContent of "Retail Companies:"
let h1Node = document.createElement("h1");
h1Node.textContent = "Retails Companies:";
document.body.appendChild(h1Node);
// Main ul
let ulNode = document.createElement("ul");
for (let company of retailCompanies) {
let liNode = document.createElement("li");
/* Code to be analyz(s)ed below*/
let textLi = document.createTextNode(company.name);
liNode.appendChild(textLi);
/* Code to be analyz(s)ed above */
ulNode.appendChild(liNode);
document.body.append(ulNode);
}
} else {
console.log(`Returned error: ${this.status}`);
}
}
But found out that I could simply do this:
xhr.onload = function() {
if (this.status === 200) {
// companies is an array of objects
let companies = JSON.parse(this.responseText);
// retailCompanies is an array of objects
let retailCompanies = companies.filter(company => company.category === "Retail");
// h1 with textContent of "Retail Companies:"
let h1Node = document.createElement("h1");
h1Node.textContent = "Retails Companies:";
document.body.appendChild(h1Node);
// Main ul
let ulNode = document.createElement("ul");
for (let company of retailCompanies) {
let liNode = document.createElement("li");
/* Code to be analyz(s)ed below */
liNode.textContent = company.name;
/* Code to be analyz(s)ed above */
ulNode.appendChild(liNode);
document.body.append(ulNode);
}
} else {
console.log(`Returned error: ${this.status}`);
}
}
Both work fine, but I wonder what is the difference (if there is any - I suppose so). I imagine that, when creating a new Element Node, it already comes with a Text Node (hence why I can use the textContent property, most likely), but why then have a createTextNode() method?
Sorry for any mistakes or if this question is (somehow) obvious, just really couldn't find anything about this and am very new to working with the DOM.
Thanks for any help with this!
(Also, I now thought of using forEach for the code, but really doesn't matter for this question. Love if you help me improve my code in any way, but please focus on the question, if possible :) )
`) and separates the text with `""`, which potentially means you could insert a `` (or other tags) in the newly added text. – Daniel A. Sep 01 '19 at 22:48