neubert
neubert

Reputation: 16802

textContent for JS without all the descendant nodes

I want to get the textContent of the current node but not of any of the descendant nodes. Any ideas as to how I might do that?

textContent does the later. nodeValue returns an empty string.

Upvotes: 2

Views: 1411

Answers (3)

Sir_baaron
Sir_baaron

Reputation: 385

I had the same issue and solved it by getting the textContent of the first child, which actually is the text. The code therefore becomes :

node.firstChild.textContent

Upvotes: 3

neubert
neubert

Reputation: 16802

I just created a span within the current node that contains that node's specific textContent and am getting the txt for that. I dunno... seems easier than going over all the node's children. Thanks for the suggestion though!

Upvotes: 0

Rafael
Rafael

Reputation: 18522

Not sure if there is an easier way, but you can always iterate over all node's children and get value of text nodes.

var text = "";
var child = element.firstChild;

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

    child = child.nextSibling;
}

console.log(text);

http://jsfiddle.net/zqbyE/

Upvotes: 4

Related Questions