我不能用:
$('div:empty')
Run Code Online (Sandbox Code Playgroud)
因为div中可能有空格.如果它没有任何东西或只有空格,我想删除它.
Jam*_*ice 11
这将返回div除空格之外没有文本的所有元素(或者由.trim新行字符删除的其他字符):
var emptyDivs = $("div").filter(function() {
return $.trim($(this).text()) === "";
});
Run Code Online (Sandbox Code Playgroud)
更新 - 基于评论
如果所讨论的任何div元素具有不包含文本的子元素(例如,img元素),则上述方法将它们包括在"空"元素集中.要排除它们,您可以使用以下内容:
var emptyDivs = $("div").filter(function() {
return $.trim($(this).text()) === "" && $(this).children().length === 0;
});
Run Code Online (Sandbox Code Playgroud)
基于@ Xeon06的答案,您可以扩展jQuery的选择器以查找没有内容的所有元素:
$.expr[':'].nocontent = function(obj, index, meta, stack){
// obj - is a current DOM element
// index - the current loop index in stack
// meta - meta data about your selector
// stack - stack of all elements to loop
// Return true to include current element
// Return false to explude current element
return !($.trim($(obj).text()).length) && !($(obj).children().length)
};
Run Code Online (Sandbox Code Playgroud)
那么用法就是:
$('div:nocontent').remove();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6424 次 |
| 最近记录: |