首页 > 解决方案 > 我的代码在 codepen 上运行,但不在我的浏览器中。我想getelementbyid,然后是控制台上的那个元素

问题描述

<!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 <-- 该脚本用于getelementbyid "hello",然后显示在控制台上。-->

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

标签: javascripthtmlwebfrontendw3c

解决方案


您应该在元素定义的下方包含 js。浏览器正在从上到下编译 html 脚本。如果你在定义的所有元素之前包含了 js 代码,那么什么都不会捕获并且它会返回错误。

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

推荐阅读