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.