How do I change the text of a span element using JavaScript?

后端 未结 13 963
悲&欢浪女
悲&欢浪女 2020-11-22 09:21

If I have a span, say:

 hereismytext 

How do I use JavaScript to change "hereism

13条回答
  •  礼貌的吻别
    2020-11-22 09:42

    EDIT: This was written in 2014. You probably don't care about IE8 anymore and can forget about using innerText. Just use textContent and be done with it, hooray.

    If you are the one supplying the text and no part of the text is supplied by the user (or some other source that you don't control), then setting innerHTML might be acceptable:

    // * Fine for hardcoded text strings like this one or strings you otherwise 
    //   control.
    // * Not OK for user-supplied input or strings you don't control unless
    //   you know what you are doing and have sanitized the string first.
    document.getElementById('myspan').innerHTML = 'newtext';
    

    However, as others note, if you are not the source for any part of the text string, using innerHTML can subject you to content injection attacks like XSS if you're not careful to properly sanitize the text first.

    If you are using input from the user, here is one way to do it securely while also maintaining cross-browser compatibility:

    var span = document.getElementById('myspan');
    span.innerText = span.textContent = 'newtext';
    

    Firefox doesn't support innerText and IE8 doesn't support textContent so you need to use both if you want to maintain cross-browser compatibility.

    And if you want to avoid reflows (caused by innerText) where possible:

    var span = document.getElementById('myspan');
    if ('textContent' in span) {
        span.textContent = 'newtext';
    } else {
        span.innerText = 'newtext';
    }
    

提交回复
热议问题