Lets say I have some html like this:
Foo
Bar
In
The trick is to modify the DOM in place to get the text, and then revert it back to the original when we're done with it. The following does the trick:
function get_visible_text(content) {
// Not so easy to get the visible text
var saved = $(content).clone();
// Remove the hidden parts
$(content).find(':hidden').remove();
// Get the remaining text
var visible_text = $(content).text();
// Now revert back to our saved version
$(content).replaceWith(saved);
return visible_text;
}
Note that @slindberg is correct, @adeneo's answer will not work because cloned objects are invisible until they are inserted into the DOM. By modifying the DOM in place, we avoid that problem.