Reputation: 32170
<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
Reputation: 18117
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.
$(this).contents().filter(function() {
return this.nodeType == 3;
}).text()
Upvotes: 0