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

后端 未结 13 870
悲&欢浪女
悲&欢浪女 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:52

    Here's another way:

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

    The innerText property will be detected by Safari, Google Chrome and MSIE. For Firefox, the standard way of doing things was to use textContent but since version 45 it too has an innerText property, as someone kindly apprised me recently. This solution tests to see if a browser supports either of these properties and if so, assigns the "newtext".

    Live demo: here

提交回复
热议问题