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

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

我的脚本标签位于 body 标签的底部,这是我在这里找到的主要解决方案。 appendChild 是否还有其他原因 运行 进入此错误?

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);
})

您需要添加一个“.”以 class 名称为目标时到 querySelector()。

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>

当使用 querySelector 时,您必须弄清楚您选择的是哪个元素,例如,在您的问题中,当您选择 class 时,您必须将 .about-me-text 的开头。对于 ID,您将在开头添加 #

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>
     <script src="rScript.js"></script>
   </body>