Lets say I have some html like this:
Foo
Bar
In
Unfortunately @adeneo's answer won't work in most cases, since cloning creates a document fragment whose children are by definition not visible (they are not attached to the document) and are therefore all removed before .text()
is called. This means that text of the element's children won't be included in the result.
The only way I've found to do this is to actually traverse all nodes top-down, omitting visually hidden nodes. Fortunately this can be expressed in a fairly concise plugin:
jQuery.fn.visibleText = function() {
return $.map(this.contents(), function(el) {
if (el.nodeType === 3) {
return $(el).text();
}
if ($(el).is(':visible')) {
return $(el).visibleText();
}
}).join('');
};
Note that this plugin assumes the selector's root element is not a text node (which is almost never the case). Also note that $(el).text()
can be replaced with el.textContent
if you don't have to support IE8.
JSFiddle