skip to Main Content

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


  1. It seems to me that the second code correct:

    const newPara = document.createElement("p");
    newPara.textContent = "You are a good person!";
    document.body.appendChild(newPara);
    

    But the first one is not correct, because getElementsByTagName() returns an HTMLCollection object, which doesn’t have an appendChild() method. So, you need to access the first element:

    const newSpanElement = document.createElement("span");
    newSpanElement.textContent = " Welcome!";
    const mainHeading = document.getElementsByTagName("h1")[0];//<- adding `[0]`
    mainHeading.appendChild(newSpanElement);
    
    Login or Signup to reply.
  2. 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 element
    So I recommend changing your code like this:

    <body>
      <script>
        document.addEventListener("DOMContentLoaded", () => {
          const newSpanElement = document.createElement("span");
          newSpanElement.innerText = " Welcome!";
          const mainHeading = document.getElementById('mainHeading');
          mainHeading.appendChild(newSpanElement);
        });
    
      </script>
      <h1 id="mainHeading"><span>T</span></h1>
    </body>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search