[英]Changing content of an H1 tag with Javascript?
我對這些話題知之甚少,但我希望你能幫助我。 本質上,我的頁面的編碼是自動設置的,我根本無法更改它,但我可以將代碼添加到它的 HEAD 部分。
現在,我的問題是......該頁面已經有一個 H1 標簽,但它被錯誤地使用了。 所以,我想更改 H1 標簽內的文本,但我需要動態地進行。 使用 Javascript 可以做到這一點嗎? 如何?
簡單地說,我想動態改變:
<h1>tag here</h1>
至:
<h1>Corrected tag here</h1>
我不確定你的情況是什么,所以我不知道你為什么只能將代碼添加到 head 標簽。 但是,您可能會在 head 標簽中添加一個 script 標簽。
像這樣的東西:
<script>
document.addEventListener('DOMContentLoaded', e => {
// select the h1 by a class, id, or even tag name
// in this example, i'm just selecting it by tag name
const h1 = document.querySelector("h1")
h1.innerText = "Correct Text"
})
</script>
(編輯:OP詢問如何通過標簽更改多個h1。
如果你想改變多個 h1,你可以這樣做:
<script>
document.addEventListener('DOMContentLoaded', e => {
const h1s = document.querySelectorAll("h1")
// This will change the innerText for the first h1 on your page
h1s[0].innerText = "Correct Text"
// This will change the innerText for the 2nd h1 on your page, etc.
h1s[1].innerText = "Some other correct text"
})
</script>
)
這應該會在加載后更改 h1 的文本。
通過向文檔中添加事件“DOMContentLoaded”的事件偵聽器,您可以確保在腳本嘗試更改其內容之前 h1 將存在。
這是一個工作示例:
<,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> <script> document,addEventListener('DOMContentLoaded'. e => { const h1 = document.querySelector("h1") h1.innerText = "Correct Text" }) </script> </head> <body> <h1>Incorrect Text</h1> </body> </html>
使用 getElementsByTagName
function change() { var h= document.getElementsByTagName("h1")[0]; h.innerText = "Corrected tag here"; }
<h1>tag here</h1> <button onclick="change()">click</button>
<,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> <script> window.onload= function() { let h1 = document.getElementsByTagName('h1') h1[0].innerText = "Corrected tag here" ///h1[1].innerText = "Corrected tag here" ////...... } </script> </head> <body> <h1>tag here</h1> </body> </html>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.