获取与jQuery唯一可见的文本 [英] Get only visible text with jquery
问题描述
可以说我有一些HTML代码是这样的:
Lets say I have some html like this:
<div id="content">Foo<span style='display:none'>hidden</span>Bar</div>
在现实中,这是比较复杂的,并采用了棱角分明 NG-隐藏
和类似的生成。我有一个需要得到所有从内容
DIV是对用户可见的文字。在这种情况下,我想获得 FooBar的
。
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
.
$('#内容)。文本()
是我发现的最接近的事情,但是这给了我 FoohiddenBar
在这种情况下。有没有好的办法得到的只是一个div的可见内容是什么?我真的需要跳过隐藏的元素文本()
功能。
$('#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.
推荐答案
创建克隆,将其添加到DOM(如slindberg指出的),删除所有隐藏要素,然后获取文本:
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();
这篇关于获取与jQuery唯一可见的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!