Nick Ginanto
Nick Ginanto

Reputation: 32170

How to ignore the innerText of child elements

<a href="#">
<span class="myspan"> Don't want this text </span>
I want this text
</a>

How can I grab just the text above without the text inside the span? Assume the span might appear or not

Upvotes: 2

Views: 1881

Answers (2)

Muhammad Umer
Muhammad Umer

Reputation: 18117

A non-Jquery solution that is faster as no cloning is Done.

Jsfiddle Demo: https://jsfiddle.net/b0424w4L/

Code

function getDirectLastText(ele) {
    var txt = null;
    [].forEach.call(ele.childNodes, function (v) {
        if (v.nodeType == 3) txt = v.textContent.replace(/^\W*\n/, '');
    });
    return txt;
}

Explanation

Even text is a node in DOM. It's call text nodes, just like html comments are also a node. Only those aren't shown. This function gets the last text node and shows it. It could have easily be extended to show all text nodes inside element and exclude all child elements.

Similar jquery version would be like this, also no cloning.

$(this).contents().filter(function() {
  return this.nodeType == 3;
}).text()

Upvotes: 0

haim770
haim770

Reputation: 49105

That's not as pretty as you may have wished, but at least it doesn't involve cloning:

$('a').contents()
      .get()
      .map(function(n) { return n.nodeType === 3 ? n.textContent.trim() : ''; })
      .join('')

See Fiddle

Upvotes: 2

Related Questions