javascript - 我的代码在 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';
解决方案
您应该在元素定义的下方包含 js。浏览器正在从上到下编译 html 脚本。如果你在定义的所有元素之前包含了 js 代码,那么什么都不会捕获并且它会返回错误。
...
// your elements are defined here.
<script src="script.js"></script>
</body>
推荐阅读
- oracle-adf - [ADF]如何根据列宽调整输入框宽度
- c# - ASP.NET Core 2.1 错误:无法使用类 Controller、属性 ViewData
- java - 使用java for循环将多个数据插入数据库
- elasticsearch - 我可以定义要快照的分片吗?
- python-3.x - 通过硒单击“更多”按钮
- javascript - 交互式多边形形状
- javascript - 按钮需要点击 2 次才能工作。- 香草 JavaScript
- dart - 如何在 Flutter 的 AppBar 中制作相同的颜色
- javascript - 尝试将多个 ID 添加到 twitter 推文功能
- c - 把字符变成数字并在c中排列数字