Get content of span

后端 未结 5 1437
北恋
北恋 2020-12-19 05:08

how can I get the contents of span ? I\'m looking for a way for all of this to be vanilla, not jQuery

javascript (and a little jQuery)

var swear_word         


        
相关标签:
5条回答
  • 2020-12-19 05:25

    Instead of using...

    text.text();
    

    Try using...

    text.innerHTML;
    

    I've only found .text() to work when you're using a jQuery selector.

     $('#myInput').text();
    
    0 讨论(0)
  • 2020-12-19 05:26

    There is an issue here:

    var text = document.getElementById('myInput');
    text.text();
    

    You never assigned the text of the input to any variable.

    Following your pattern above, you could do:

    var txt = document.getElementById('myInput'),
        txt = text.text();
    

    The second variable updates the previous variable 'txt' to hold the text of the original 'txt' variable, which was a selector.

    You could do this as well (vanilla javascript, jsfiddle):

    var txt = document.getElementById('myInput').innerHTML;
    
    //or
    
    var txt = document.getElementById('myInput').textContent;
    
    0 讨论(0)
  • 2020-12-19 05:31
    var text = (document.getElementById("myInput")).innerHTML
    

    or the abridged form:

    var text = $('#myInput').text()
    
    0 讨论(0)
  • 2020-12-19 05:32

    You can use textContent

    Taken from MDN:

    // Given the following HTML fragment:
    //   <div id="divA">This is <span>some</span> text</div>
    
    // Get the text content:
    var text = document.getElementById("divA").textContent;
    // |text| is set to "This is some text".
    
    // Set the text content:
    document.getElementById("divA").textContent = "This is some text";
    // The HTML for divA is now:
    //   <div id="divA">This is some text</div>
    
    0 讨论(0)
  • 2020-12-19 05:36

    Give this a shot:

    var input = document.getElementById("myInput");
    var text = input.innerHTML;
    
    0 讨论(0)
提交回复
热议问题