我希望创建一个数组,其中包含div中包含文本字符串的所有html元素,例如
<p>some string</p>.
我不想拿到字符串,我想要数组项成为元素(在本例中,将是p节点)。我事先不知道字符串会是什么,所以无法寻找匹配的字符串值。我也不希望空文本节点出现在数组中。
谢谢!
$("#my_div *").filter(function()
{
var $this = $(this);
return $this.children().length == 0 && $.trim($this.text()).length > 0;
})
这个版本不会返回包含文本元素的父元素,只会返回最后一级的元素。
可能不是最快的方法,但在 StackOverflow 主页上表现得相当不错 :)
在您的情况下,自定义选择器可能会很有帮助:
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;
};
$('#someDiv :hasText') // will contain all elements with text nodes (jQuery object)
$('#someDiv :hasText').get() // will return a regular array of plain DOM objects
$("#theDiv > :not(:empty)").get();
$("#theDiv > :not(:empty, :has(*))").get();
$("#theDiv > :not(:has(*))").filter(function() {
return $.trim(this.innerHTML).length > 0;
}).get();
var array = [];
var divSelector = "div.mine";
$(divSelector).contents().each(function()
{
// If not an element, go to next node.
if (this.nodeType != 1) return true;
var element = $(this);
if ($.trim(element.text()) != "")
array.push(element);
});
array
是包含一些文本元素的数组。
d 是您想要查找内容的 div 元素
v 是一个空数组
i 必须从 0 开始。
$.trim 用于避免获取到只包含空格的节点。
$("*",d).filter( function() {
return $.trim($(this).text()) != ""
} ).each( function() {
v[i] = $(this).text();
i++;
} );
还可以使用v.push($(this))...这是我完全忘记了的事情。
$(function() {
var array = new Array();
$("#testDiv *").each(function(x, el) {
if ($.trim($(el).text()) != '' ) {
array.push(el);
}
});
alert(array.length);
});
var matches = new Array();
$('#start_point *:contains(' + text + ')').each(function(i, item) {
matches.push( item );
}