Home  >  Q&A  >  body text

javascript - How to get only the content in the current box in js?

The picture is as above, and then paste the html structure

<p class="second">web
    <p class="third">javascript</p>
    <p class="third">css
        <p class="forth">css2.0</p>
        <p class="forth">css3</p>
    </p>
    <p class="third">html</p>
    5555
    <p class="third">可视化</p>
    555
</p>

Suppose I have taken the outermost frame of second
Now I want to get the "web", "555" (a), "5555(b)" How to store the anonymous text in a variable?
I tried innerText will get the text in the child node
Use childNodes[0].nodeValue will only get the first text node
Is it feasible to use if to determine whether nodeType is a text node?
I don’t know if there is a better way to directly get the text of the current box without getting the text in the child node~

怪我咯怪我咯2648 days ago669

reply all(1)I'll reply

  • ringa_lee

    ringa_lee2017-06-26 10:53:24

    var t = document.getElementsByClassName('second')[0];
    
    t.childNodes.forEach(function(v) {
        if(v instanceof Text) {
            console.log(v.data);
            console.log(v.wholeText);
        }
    });

    Among them, the text node is an instance of Text(), and you can use data or wholeText to get text of type String.

    reply
    0
  • Cancelreply