How to dynamically change a web page's title?

前端 未结 19 1728
遇见更好的自我
遇见更好的自我 2020-11-22 08:05

I have a webpage that implements a set of tabs each showing different content. The tab clicks do not refresh the page but hide/unhide contents at the client side.

No

19条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-22 08:23

    There are many ways you can change the title, the main two, are like so:

    The Questionable Method

    Put a title tag in the HTML (e.g. Hello), then in javascript:

    let title_el = document.querySelector("title");
    
    if(title_el)
        title_el.innerHTML = "World";
    

    The Obviously Correct Method

    The simplest of all is to actually use the method provided by the Document Object Model (DOM)

    document.title = "Hello World";
    

    The former method is generally what you would do to alter tags found in the body of the document. Using this method to modify meta-data tags like those found in the head (like title) is questionable practice at best, is not idiomatic, not very good style to begin with, and might not even be portable. One thing you can be sure of, though, is that it will annoy other developers if they see title.innerHTML = ... in code they are maintaining.

    What you want to go with is the latter method. This property is provided in the DOM Specification specifically for the purpose of, as the name suggests, changing the title.

    Note also that if you are working with XUL, you may want to check that the document has loaded before attempting to set or get the title, as otherwise you are invoking undefined behavior (here be dragons), which is a scary concept in its own right. This may or may not happen via JavaScript, as the docs on the DOM do not necessarily pertain to JavaScript. But XUL is a whole 'nother beast, so I digress.

    Speaking of .innerHTML

    Some good advice to keep in mind would be that using .innerHTML is generally sloppy. Use appendChild instead.

    Although two cases where I still find .innerHTML to be useful include inserting plain text into a small element...

    label.innerHTML = "Hello World";
    // as opposed to... 
    label.appendChild(document.createTextNode("Hello World"));
    // example:
    el.appendChild(function(){
        let el = document.createElement("span");
        el.className = "label";
        el.innerHTML = label_text;
        return el;
    }());
    

    ...and clearing out a container...

    container.innerHTML = "";
    // as opposed to... umm... okay, I guess I'm rolling my own
    [...container.childNodes].forEach(function(child){
        container.removeChild(child);
    });
    

提交回复
热议问题