我有一个 html 文件(从 docx 转换而来),它没有任何类名或 id。如何使用 JS 设置样式?例如,如果我需要更改以下文件 HTML 的标题颜色
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="./script.js"></script>
<title>Document</title>
</head>
<body>
<h1>This is the heading</h1>
<p>Hello, my name is xyz and this is a para</p>
</body>
</html>
这是我尝试过的,但document.getElementByTagName()
没有返回类似的元素document.getElementById()
console.log('hello world');
Heading = document.getElementsByTagName('h1');
console.log(Heading);
Heading.style.color = 'blue';
编辑:我尝试了下面的代码,但它返回未定义
console.log('hello world');
Heading = document.getElementsByTagName('h1')[0];
console.log(Heading);
Heading.style.color = 'blue';
请像这样更新您的代码。您在 html 之前导入了脚本。有两种解决方案。首先你必须在 html 之后导入脚本或使用
window.addEventListener
window.addEventListener('load', () => {
const heading = document.querySelector('h1');
heading.style.color = 'blue';
});
<h1>This is the heading</h1>
<p>Hello, my name is xyz and this is a para</p>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句