如何使用 Javascript 替换/更改 <h1></h1> 中的标题文本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18334307/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 11:31:23  来源:igfitidea点击:

How Do I Replace/Change The Heading Text Inside <h1></h1>, Using Javascript?

javascripthtmlhtml-heading

提问by noobprogrammer

How do I change/replace the text: "Hello" using javascript to say "Goodbye" instead?

如何更改/替换文本:“你好”使用 javascript 说“再见”?

<h1 class="titlearea win-type-ellipsis" id="title">
     <span class="pagetitle" >
            Hello
     </span>
</h1>

回答by mithunsatheesh

document.getElementsByClassName("pagetitle")[0].innerHTML = "Goodbye";

Here is a working fiddle.

这是一个工作小提琴

回答by SmokeyPHP

document.getElementById('title').getElementsByTagName('span')[0].innerHTML = 'Goodbye';

回答by Emissary

If you're happy to give legacy browsers the finger (preferable):

如果您很乐意为旧版浏览器提供帮助(最好):

document.querySelector('#title .pagetitle').innerHTML = 'Goodbye';

Support:

支持:

Chrome  Firefox (Gecko)  Internet Explorer  Opera  Safari (WebKit)
1       3.5 (1.9.1)      8                  10     3.2 (525.3)
        bug 416317                                 WebKit bug 16587

See also: document.querySelectorAll

也可以看看: document.querySelectorAll

回答by Runedrake

document.getElementsByClassName("pagetitle")[0].textContent = "Goodbye";

or

或者

document.getElementsByClassName("pagetitle")[0].innerHTML = "Goodbye";

or

或者

document.getElementById('title').getElementsByTagName('span')[0].textContent = 'Goodbye';

or

或者

document.getElementById('title').getElementsByTagName('span')[0].innerHTML = 'Goodbye';

or

或者

document.getElementById('title').getElementsByClassName("pagetitle")[0].textContent = "Goodbye";

or

或者

document.getElementById('title').getElementsByClassName("pagetitle")[0].innerHTML = "Goodbye";

回答by Naveen Kumar Alonekar

Here is JSBin

这是JSBin

Change by using getElementsByTagName('span')

使用getElementsByTagName('span')更改

document.getElementsByTagName('span')[0].innerHTML = 'Goodbye';