Reputation: 1211
<div>
some text I want
<span><sup>text I don't want</sup></span>
</div>
Above is some example html. I want to be able to select just the text of the div without the child html text that is located in the span. Is there any simple way of doing this or am I going to have to come up with some way to hack away at the markup?
I've tried using jquery selectors to select just the div but when I end up calling the .text() method you end up with all of the text again... Am I missing something extremely obvious?
Upvotes: 1
Views: 195
Reputation: 147363
Just collect the text of the immediate child nodes:
function getImmediateText(el) {
var node, nodes = el.childNodes;
var text = '';
for (var i=0, iLen=nodes.length; i<iLen; i++) {
node = nodes[i];
if (node.nodeType == 3) {
text += node.data;
}
}
// You may want to trim excess white space here
return text;
}
That will work in every browser and doesn't need library support.
Upvotes: 0
Reputation: 53781
jQuery is completely unnecessary. Strip all HTML:
var text = node.innerHTML.replace(/<.+>/, '');
Demo with jQuery to select the div.
Upvotes: 0
Reputation: 39808
Fully explained answer with the example can be found here: http://jsfiddle.net/xHcPU/
//elem.childNodes is a NodeList containing all child nodes of the array
//This includes every node - text and elements
// https://developer.mozilla.org/En/DOM/Node.childNodes
var childNodes = document.getElementById( 'special' ).childNodes;
//arr.reduce receives an array-like object and a callback
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/Reduce
//We use func.call to call arr.reduce with the childNodes as the this variable
// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/call
var out = [].reduce.call( childNodes, function ( ret, child ) {
//if a node's nodeType is 3, you can safely say it's a text node
// https://developer.mozilla.org/en/nodeType
if ( child.nodeType === 3 ) {
ret += child.nodeValue.trim();
}
//if it's any other node, we just ignore it
return ret;
}, '' );
//out will now contain the string you seek
Do note that the two ES5 functions used here, Array.prototype.reduce
and String.prototype.trim
, can be easily replaced by a shim, your own implementation or, if existant, a jQuery equivalent. I do not recall a reduce
equivalent, but I do believe there exists a trim
one.
Upvotes: 0
Reputation: 79830
May be something like below should get you the text,
var justText = $('div').contents().filter(function () {
if (this.nodeType == 3) return true;
}).text();
Note that this would also return you the line breaks and white space.
You can use $.trim
to get rid of those,
justText = $.trim(justText);
Upvotes: 2