Jquery用文本查找所有元素
扫描所有DOM的最佳方法是什么,找到任何包含文本的元素并将其包装在span类中? 感谢名单
要包装包含除空白之外的所有文本节点:
$('body *').contents().filter(function() { return (this.nodeType == 3) && this.nodeValue.match(/\S/); }).wrap("")
要包装所有文本节点,包括仅包含空格的节点:
$('body *').contents().filter(function() { return (this.nodeType == 3) && this.nodeValue.length > 0; }).wrap("")
您可以使用.each迭代所有元素:
$('*').each(function(){ if($(this).text()) { $(this).wrapInner(''); } })
我没有测试那段代码,但它很简单。 您需要了解的只有.each , wrapInner和* selector。 jQuery文档在这里非常有用。