1
<p id='1'></p>
<p id='1a'><br /></p>
<p id='3success'><b>Match this</b></p>
<p id='3fail'><b>Match this</b> but not now because of this test</p>

我有一些逻辑需要跳过满足以下条件的元素

  1. 没有 html
  2. 只有 br 或 nbsp
  3. 只有特定类型的子元素 (b,i,img)

我可以轻松处理 1/2,但第三个我遇到了麻烦。我知道如何断言子部分,$('#3fail').children().length但我不知道如何确定是否有附加文本。

关于如何验证 3 的任何建议?我正在一个简单的.each函数中处理元素

$('p').each(function(){ 
     var element = $(this)
     if(matchesCondition(element)){
        doLogic(element)
     } 
}); 

笔记

有人发布了答案并获得了很多赞成票,但它不起作用。这是一个测试答案的小提琴。

http://jsfiddle.net/ncapito/k87rc/

我能够修复@Kolink 的答案

http://jsfiddle.net/ncapito/9D3tg/

var getNontextNodes;
//coffeescript generated
getNontextNodes = function (nodes) {
  var cnt, n, _i, _len;
  cnt = 0;
  for (_i = 0, _len = nodes.length; _i < _len; _i++) {
    n = nodes[_i];
    if (n.textContent.trim()) {
      cnt++;
    }
   }
  return cnt;
};

$("p").each(function () {
  if (
    (this.children.length === this.childNodes.length)
   || 
     (getNontextNodes(this.childNodes) === this.children.length)) 
       $(this).append("<b style='color:green'>Success</b>");
  else 
    $(this).append("<b style='color:red'>Failed</b>");
});
4

1 回答 1

6

您可以通过检查来检查元素是否只有子元素
if( this.children.length == this.childNodes.length),因为children[]只计算元素子元素,同时也childNodes[]包括文本节点。

清除此步骤后,您可以遍历children[]数组并检查它们tagName是否在您的列表中。

编辑:我刚刚注意到,这将不允许元素之间的任何空格,例如换行符。如果您想允许空格但不允许实际文本,请尝试以下检查:
if( !(this.textContent || this.innerText).match(/\S/))

不,那行不通。但是,这将:

var filter = [].filter ? [].filter : function(cb) {for( var i=0, l=this.length, ret=[]; i<l; i++) {if(cb(this[i])) ret.push(this[i]);} return ret;};
$("p").each(function(){
    if( this.children.length == this.childNodes.length || filter.call(this.childNodes,function(n) {return n.nodeType == 3 && n.nodeValue.match(/\S/);}).length == 0)
        $(this).append("<b style='color:green'>Success</b>")
   else
       $(this).append("<b style='color:red'>Failed</b>")
});

演示

于 2013-06-20T16:27:16.400 回答