Home  >  Q&A  >  body text

javascript - A question about InnerText?

I want to use InnerText to get the text content of a certain p node, but there are several child nodes inside this node. As a result, using InnerText will also get the text of its child nodes. How to solve it?

For example:

<p id="p"><p>这不是我想要的<hr /></p>这才是我想要的</p>

What I want to get is the part of "This is what I want". What do you mean?

迷茫迷茫2639 days ago911

reply all(1)I'll reply

  • 三叔

    三叔2017-07-05 10:59:20

    First use document.getElementById('p').childNodes
    to get all the child elements, then traverse the node whose nodeType is 3 (3 is the text node), and finally get its nodeValue value.
    Be careful when writing like this

    <p id="p">
        <p>这不是我想要的<hr /></p>这才是我想要的
    </p>
    

    childNodes will get empty text nodes and need to be filtered.
    There is also a compatibility issue with innerText.

    I can only think of this method now.

    reply
    0
  • Cancelreply