Search code examples
javascripthtmlarraysdomappendchild

Uncaught TypeError: Cannot read properties of null (reading 'appendChild'); Persistent Error


My script tag is at the bottom of my body tag which is the main solution I have found on here. Is there any other reasons appendChild would be running into this error?

Html:

     <section class="section-2">
       <p class="about-me-text"></p>
     </section>
     <script src="rScript.js"></script>
   </body>

Javascript:

const aboutMeText = document.querySelector("about-me-text");
const aboutMeTextContent = 'I am a creative designer, who dabbles in both website 
creation & digital art design. Contact me to start a creative project or website 
today.'

Array.from(aboutMeTextContent).forEach(char => {
 const span = document.createElement("span");
 span.textContent = char;
 aboutMeText.appendChild(span);
})

Solution

  • You need to add a "." to querySelector() when targeting a class name.

    const aboutMeText = document.querySelector(".about-me-text");
    const aboutMeTextContent = `I am a creative designer, who dabbles in both website
      creation & digital art design. Contact me to start a creative project or website
      today.`
    
    Array.from(aboutMeTextContent).forEach(char => {
      const span = document.createElement("span");
      span.textContent = char;
      aboutMeText.appendChild(span);
    })
    <section class="section-2">
      <p class="about-me-text"></p>
    </section>