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

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

    For modern browsers you should use:

    document.getElementById("myspan").textContent="newtext";
    

    While older browsers may not know textContent, it is not recommended to use innerHTML as it introduces an XSS vulnerability when the new text is user input (see other answers below for a more detailed discussion):

    //POSSIBLY INSECURE IF NEWTEXT BECOMES A VARIABLE!!
    document.getElementById("myspan").innerHTML="newtext";
    

提交回复
热议问题