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

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

If I have a span, say:

 hereismytext 

How do I use JavaScript to change "hereism

13条回答
  •  自闭症患者
    2020-11-22 10:01

    Using innerHTML is SO NOT RECOMMENDED. Instead, you should create a textNode. This way, you are "binding" your text and you are not, at least in this case, vulnerable to an XSS attack.

    document.getElementById("myspan").innerHTML = "sometext"; //INSECURE!!
    

    The right way:

    span = document.getElementById("myspan");
    txt = document.createTextNode("your cool text");
    span.appendChild(txt);
    

    For more information about this vulnerability: Cross Site Scripting (XSS) - OWASP

    Edited nov 4th 2017:

    Modified third line of code according to @mumush suggestion: "use appendChild(); instead".
    Btw, according to @Jimbo Jonny I think everything should be treated as user input by applying Security by layers principle. That way you won't encounter any surprises.

提交回复
热议问题