我有一個 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';

uj5u.com熱心網友回復:
你也可以試試document.querySelector()。
<!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" />
<title>Document</title>
</head>
<body>
<h1>This is the heading</h1>
<p>Hello, my name is xyz and this is a para</p>
</body>
<script type="text/javascript">
const header = document.querySelector('h1');
console.log(header);
header.style.color = 'blue';
</script>
</html>
需要注意的另一件事是 - 我們需要等待頁面加載,否則您的 javascript 代碼將首先運行并回傳未定義。
您可以使用以下任何一種方式確保 javascript 在頁面加載后運行 -
- 添加事件監聽器 –
document.addEventListener("load", FUNCTION); - 將 onl oad 添加到 body 標簽 -
<body onl oad="FUNCTION()"> - 推遲腳本——
<script src="SCRIPT.js" defer> - 最后,將腳本放在頁面的最底部——盡管這不是“頁面加載后”。
uj5u.com熱心網友回復:
您的代碼中的問題是getElementsByTagName回傳一個陣列,但您使用的就像它是一個元素一樣。
試試這個:
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>
uj5u.com熱心網友回復:
請像這樣更新您的代碼。您在 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>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/461789.html
標籤:javascript html css
