最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How can I change the content of the "h1" tag of an html page using javascript? - Stack Overflow

programmeradmin0浏览0评论

I need to change the content of all "h1" tags in my html file when the page load using javascript.

So I write the following code

window.onload = function () {
    var h1html = document.createElement("h1");
    var h1htmltext = document.createTextNode("header 1");

    h1html.appendChild(h1htmltext);

    document.getElementsByTagName("h1").appendChild(h1html);
};

I need to change the content of all "h1" tags in my html file when the page load using javascript.

So I write the following code

window.onload = function () {
    var h1html = document.createElement("h1");
    var h1htmltext = document.createTextNode("header 1");

    h1html.appendChild(h1htmltext);

    document.getElementsByTagName("h1").appendChild(h1html);
};
Share Improve this question asked Jun 23, 2013 at 15:21 HTML ManHTML Man 9374 gold badges17 silver badges40 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 3

If you're sure you only have one h1 tag you could simply do

window.onload = function () {
    document.getElementsByTagName("h1")[0].innerHTML = "header 1";
}

if multiple h1 tags are present you could do

window.onload = function () {
    var h1Elems = document.getElementsByTagName("h1");
    var pos;
    for (pos in h1Elems) {
        h1Elems[pos].innerHTML = "header 1";
    }
}

Use this:

for(var i = 0, elems = document.getElementsByTagName('h1'); i < elems.length; i++) { 
   elems[i].innerHTML = "new";
}

fiddle

You need to change the innerHTML of each elements, as such

function changeall(){
    var headers=document.getElementsByTagName("h1");
    var newheadertext="hello";
    for(var i in headers){
         headers[i].innerHTML=newheadertext;
    }
}

getElementsByTagName returns a node list; you need to loop through it.

var headers = document.getElementsByTagName("h1");

for(var i = 0; i < headers.length; i++) {
    var header = headers[i];
    var text = document.createTextNode("header 1");

    while(header.childNodes.length) {
        header.removeChild(header.firstChild);
    }

    header.appendChild(text);
}

I made a few assumptions there:

  • You don’t actually want to nest headers
  • You want to replace the content
  • You want an old-standards-pliant way

If you don’t need support for old browsers, just use textContent:

var headers = document.getElementsByTagName("h1");

for(var i = 0; i < headers.length; i++) {
    headers[i].textContent = "header 1";
}
发布评论

评论列表(0)

  1. 暂无评论