Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get only visible text with jquery

Lets say I have some html like this:

<div id="content">Foo<span style='display:none'>hidden</span>Bar</div>

In reality this is more complicated and generated by angular using ng-hide and similar. I have a need to get all of the text from the content div that is visible to the user. In this case I would like to get FooBar.

$('#content').text() is the closest thing I have found, but that gives me FoohiddenBar in this case. Is there a good way to get just the visible contents of a div? I really need a text() function that skips hidden elements.

like image 208
captncraig Avatar asked Dec 08 '22 14:12

captncraig


1 Answers

create a clone, add it to the DOM (as pointed out by slindberg), remove all hidden elements, and then get the text :

var clone = $('#content').clone();

clone.appendTo('body').find(':hidden').remove();

var text = clone.text();

clone.remove();

FIDDLE

like image 156
adeneo Avatar answered Dec 26 '22 09:12

adeneo