代码之家  ›  专栏  ›  技术社区  ›  Mircea

Jquery查找包含文本的所有元素

  •  10
  • Mircea  · 技术社区  · 16 年前

    桑克斯

    2 回复  |  直到 16 年前
        1
  •  14
  •   Mario Menger    16 年前

    要包装包含除空白以外的内容的所有文本节点,请执行以下操作:

    $('body *').contents().filter(function() { 
        return (this.nodeType == 3) && this.nodeValue.match(/\S/); 
    }).wrap("<span />")
    

    $('body *').contents().filter(function() { 
        return (this.nodeType == 3) && this.nodeValue.length > 0; 
    }).wrap("<span />")
    
        2
  •  1
  •   dzida    16 年前

    你可以用 .每个

    $('*').each(function(){
        if($(this).text())
        {
            $(this).wrapInner('<span />');
        }
    })
    

    我没有测试那段代码,但它非常简单。你需要了解的是 , 包装机 和*选择器。jquerydocs在这里非常有用。