I am learning web development and has just started learning DOM. Right now I’m facing a challenge which is, when I use document.createElement()
and appendChild()
in VScode it doesn’t work. But when i do it directly on Chrome browser console it works as I expected. Is there something I’m doing wrong? Or can I write this code and get the expected result while using the browser console only?
Here is my code snippet:
const newSpanElement = document.createElement("span");
newSpanElement.textContent = " Welcome!";
const mainHeading = document.getElementsByTagName("h1");
mainHeading.appendChild(newSpanElement);
And:
const newPara = document.createElement("p");
newPara.textContent = "You are a good person!";
document.body.appendChild(newPara);
None of the above method gave me the expected output in the browser when written in VS code, but both worked perfectly when written directly in the browser console. Please, what could possibly be the reason for this?
Thank you so much in advance for your help!
Note:
I also used .innerHTML
, .createTextNode()
, but they all turned out to be the same.
2
Answers
It seems to me that the second code correct:
But the first one is not correct, because
getElementsByTagName()
returns anHTMLCollection
object, which doesn’t have anappendChild()
method. So, you need to access the first element:for getting dom elements better to use ids and
document.getElementById()
instead of tags or classes, this is the collection and there can be multiple elements there are no warranties that you get the needed elementSo I recommend changing your code like this: