【发布时间】:2011-09-22 08:33:22
【问题描述】:
我正在尝试将一个类应用于所有包含文本或其中包含文本和其他 dom 元素的元素。至少元素内必须有某种文本。
这个 div 应该得到类:
<div class="theClass">Some text</div>
这个 div 也应该得到类:
<div class="theClass">Some text<div class="theClass more">More text</div></div>
但是这个应该只给子div类:
<div class=""><div class="theClass more">More text</div></div>
目前我正在使用 :hasText 选择器,我在这里找到了 finding elements with text using jQuery。
jQuery.expr[':'].hasText = function(element, index) {
// if there is only one child, and it is a text node
if (element.childNodes.length == 1 && element.firstChild.nodeType == 3) {
return jQuery.trim(element.innerHTML).length > 0;
}
return false;
};
但它只返回包含文本的元素。我喜欢包含文本和其他元素(如果有的话)的元素。
谢谢!
【问题讨论】: