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

后端 未结 13 646
悲&欢浪女
悲&欢浪女 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:50
    document.getElementById('myspan').innerHTML = 'newtext';
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-11-22 09:56

    You can do

     document.querySelector("[Span]").textContent = "content_to_display"; 

    0 讨论(0)
  • 2020-11-22 09:58

    You may also use the querySelector() method, assuming the 'myspan' id is unique as the method returns the first element with the specified selector:

    document.querySelector('#myspan').textContent = 'newtext';
    

    developer.mozilla

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 10:03

    Like in other answer, innerHTML and innerText are not recommended, it's better use textContent. This attribute is well supported, you can check it this: http://caniuse.com/#search=textContent

    0 讨论(0)
提交回复
热议问题