How to get < span> value?

前端 未结 7 2064
温柔的废话
温柔的废话 2021-02-07 10:41

There are a piece of code,but can not use tag.

So,how do I get to the 1 2 3 4?

相关标签:
7条回答
  • 2021-02-07 11:19

    No jQuery tag, so I'm assuming pure JavaScript

    var spanText = document.getElementById('targetSpanId').innerText;
    

    Is what you need

    But in your case:

    var spans = document.getElementById('test').getElementsByTagName('span');//returns node-list of spans
    for (var i=0;i<spans.length;i++)
    {
        console.log(spans[i].innerText);//logs 1 for i === 0, 2 for i === 1 etc
    }
    

    Here's a fiddle

    0 讨论(0)
  • 2021-02-07 11:25
    <div id="test">
        <span>1</span>
        <span>2</span>
        <span>3</span>
        <span>4</span>
    </div>
    <div id="test2"></div>
    
    <script type="text/javascript">
        var getDiv = document.getElementById('test');
        var getSpan = getDiv.getElementsByTagName('span');​​​
        var divDump = document.getElementById('test2');
    
        for (var i=0; i<getSpan.length; i++) {
            divDump.innerHTML = divDump.innerHTML + ' ' + getSpan[i].innerHTML;
        }
    </script>
    

    0 讨论(0)
  • 2021-02-07 11:30
    var test = document.getElementById( 'test' );
    
    // To get the text only, you can use "textContent"
    console.log( test.textContent ); // "1 2 3 4"
    

    textContent is the standard way. innerText is the property to use for legacy IE. If you want something as cross browser as possible, recursively use nodeValue.

    0 讨论(0)
  • 2021-02-07 11:32

    You can use querySelectorAll to get all span elements and then use new ES2015 (ES6) spread operator convert StaticNodeList that querySelectorAll returns to array of spans, and then use map operator to get list of items.

    See example bellow

    ([...document.querySelectorAll('#test span')]).map(x => console.log(x.innerHTML))
    <div id="test">
        <span>1</span>
        <span>2</span>
        <span>3</span>
        <span>4</span>
    <div>

    0 讨论(0)
  • 2021-02-07 11:37

    Try this

    var div = document.getElementById("test");
    var spans = div.getElementsByTagName("span");
    
    for(i=0;i<spans.length;i++)
    {
      alert(spans[i].innerHTML);
    }
    
    0 讨论(0)
  • 2021-02-07 11:39

    Pure javascript would be like this

    var children = document.getElementById('test').children;
    

    If you are using jQuery it would be like this

    $("#test").children()
    
    0 讨论(0)
提交回复
热议问题