使用 jQuery 查找带有文本的元素
我想创建一个包含文本字符串的 div 中所有 html 元素的数组,例如
<p>some string</p>.
我不想获取字符串,我希望数组项成为元素(在示例中,将是p 节点)。 我事先不知道字符串是什么,所以我无法查找匹配的字符串值。 我也不希望空文本节点出现在数组中。
谢谢!
I want to create an array of all the html elements within a div that contain text strings, such as
<p>some string</p>.
I don't want to get hold of the strings, I want the array items to be the elements (in the example, would be the p node). I do not know before hand what the strings will be, so I can't look for string values to match. I also don't want empty text nodes to end up in the array.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
此版本不会返回包含具有文本的元素的父元素,仅返回最后一级元素。
可能不是最快的,但在 StackOverflow 主页上运行得很好:)
This version will not return parent elements that contains the elements having texts, only the last level elements.
May not be the fastest but works quite well on StackOverflow homepage :)
自定义选择器可能对您的情况有所帮助:
之后,您可以简单地执行以下操作:
我假设您只是尝试选择内部仅包含文本的元素。
A custom selector could be helpful in your case:
After that, you can simply do this:
I am assuming that you are only trying to select elements that have ONLY text inside of them.
您可以使用 not 和空选择器来获取非空元素,同时可以使用 get 转换为数组。
上面的选择器获取“theDiv”的所有非空子元素(即它们要么有child 或 text),然后将匹配的集合转换为数组。
如果您只想要其中包含文本的元素,这应该可以...
要摆脱包含空格的元素,您可以使用过滤器
You can make use of not and the empty selectors to get the non-empty elements while converting to an array can be achieved using get
The above selector gets all the children elements of "theDiv" and that aren't empty (i.e. they either have children or text) and then converts the matched set to an array.
If you want only elements that have text inside them, this should work...
To get rid of elements that have whitespace you can make use of filter
您可以循环遍历 children 并获取具有 .text() 值
!= ""
You could cycle through the children and grab everything that has a .text() value
!= ""
array
是其中包含一些文本的元素数组。array
is the array of elements that have some text in them.d 是要在其下查找内容的 div
v 是一个空数组
我你必须从 0 开始。
使用 $.trim 是为了避免得到只有空白的节点。
人们还可以使用 v.push($(this))...这是我完全忘记的事情。
d is the div under which you want to find things
v is an empty array
i you have to start out at 0.
The $.trim is used so that you don't get nodes that are just whitespace.
One can also use v.push($(this))...which is something that totally slipped my mind.
使用 :contains 选择器:
Use the :contains selector: