我的代码可以在 codepen 上运行,但不能在我的浏览器上运行。我想 getelementbyid 然后是控制台上的那个元素

my code is working on codepen but not in my browser. i wanted to getelementbyid and then then that element on console

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Assignment 4</title>
    <script src="script.js"></script>
  </head>
  <body>
        <h1>Biryani</h1>
        <h2 id="hello">Rohan</h2>
        <p>Biryani is Pakistan's special dish. Main Ingredients are rice and chicken.</p>
  </body>
</html>

script.js <-- 该脚本用于通过id“hello”获取元素,然后显示在控制台上。-->

var myname = document.getElementById("hello");
console.log(myname.innerHTML);
const el = document.querySelector('h2');
el.textContent = 'Assignment 4';

您应该在元素定义下方包含 js。 浏览器正在从上到下编译 html 个脚本。如果您在定义的所有元素之前包含 js 代码,那么什么也抓不到并且它 returns 错误。

...
// your elements are defined here.
<script src="script.js"></script>
</body>

代码正确。您只需要在关闭 body 标签之前移动您的脚本标签。

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Assignment 4</title>
  </head>
  <body>
    <h1>Biryani</h1>
    <h2 id="hello">Rohan</h2>
    <p>
      Biryani is Pakistan's special dish. Main Ingredients are rice and chicken.
    </p>
    <script src="./script.js"></script>
  </body>
</html>