如何检测一个元素是否为空但有空格和回车符并用 JavaScript / jQuery 修剪它们?
我正在尝试使用 $.trim()
修剪空元素中的空格,以便我可以检查元素的长度以查看其中是否有文本内容,如果没有则将其删除来自 DOM。
某些元素返回的长度大于 0,因为它们中包含空格和/或回车符,而这就是它们中包含的全部内容。
我基本上需要找到并删除任何空标签(当它们中没有任何内容时)。
我不认为有人知道一种简单快速的方法来检查并删除页面主要内容中的任何空标签,无论它们是否包含任何空白字符? 我确信一定有办法。
I'm trying to use $.trim()
to trim whitespace in empty elements so I can check the length of an element to see if it has text content in it and if it does not then remove it from the DOM.
Some elements are returning a length of greater than 0 because they have spaces and/or carriage returns in them which is all that is contained in them.
I basically need to find and remove any empty tags when they have nothing in them.
I don't suppose anyone knows of a simple quick way to just check for and remove any empty tags in the main content of a page, whether they contain any whitespace chars or not by any chance?
I'm sure there must be a way.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您只想检查
body
中的元素,否则script
标记和其他非内容元素也会被删除:http://jsfiddle.net/6zdNf/1/。You'd want to check for elements in the
body
only, since otherwisescript
tags and other non-content elements also get removed: http://jsfiddle.net/6zdNf/1/.只需使用带有函数的 jQuery 过滤器即可:
使用此代码后,您将只剩下带有文本的 div!请谨慎使用图像,因为它们没有任何文本!
正则表达式
/\S/gi
测试非空格字符。空标签将不匹配并返回 false。Simply use jQuery filter with a function:
After using this code, you'll only have divs left with text in it! Use with caution on images, since they do not have any text!
The regular expression
/\S/gi
test for a non-space character. Empty tags won't match and will return false.不过,不要指望它运行得非常高效。
Don't expect it to run very efficiently, though.
试试这个:
您可能需要进一步微调选择器,但它应该可以做到。
Try this:
You may need to further fine-tune the selector a bit, but it should do it.