0
<div class="classDiv">

<span id="mySpan"> TEXT 1 </span> TEXT 2

</div>

Using document.querySelectorAll(".classDiv")[0].textContent

Returns = TEXT 1 TEXT 2

How can i get only TEXT 2?

I tried with :not(span) without success.

Thanks

1

1 Answer 1

3

There’s nothing built-in that I’m aware of, but you can add a function to extract text nodes that are direct children of an element:

function getDirectText(node) {
    var text = '';

    for (var i = 0; i < node.childNodes.length; i++) {
        var child = node.childNodes[i];

        if (child.nodeType === 3) {  // Node.TEXT_NODE
            text += child.nodeValue;
        }
    }

    return text;
}

and then:

var text = getText(document.getElementsByClassName('classDiv')[0]);

You might want to trim the result of whitespace, too.

Sign up to request clarification or add additional context in comments.

2 Comments

I got distracted while writing my own answer, wandered off to come back and find yours; since my own answer and yours are only marginally different it seems pointless adding my own, so if you consider this a useful alternative I'd be quite happy if you wanted to add it to your answer: jsfiddle.net/davidThomas/num9zf3b :) (although I chose to return the Array, rather than joining it together.)
@DavidThomas: I think that stands on its own as a nice ES6 way; if you added it, I’d vote for it. =)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.