Javascript 如何选择除元素以外的所有子元素
我有一个包含3个子元素的元素。让我说Javascript 如何选择除元素以外的所有子元素,javascript,jquery,Javascript,Jquery,我有一个包含3个子元素的元素。让我说 <div class="parent"> <div class="firstChild">firstChild</div> SecondChild <ul><li>thrid child</li></ul> </div> 长子 次子 第三个孩子 在这个例子中,我需要选择前两个孩子,而不是UL。如何通过jquery执行。此选择器应该可以执行此操作 $("
<div class="parent">
<div class="firstChild">firstChild</div>
SecondChild
<ul><li>thrid child</li></ul>
</div>
长子
次子
第三个孩子
在这个例子中,我需要选择前两个孩子,而不是UL。如何通过jquery执行。此选择器应该可以执行此操作
$(".parent *").not("ul")
试试这个:
$(".parent").children();
您可以使用
:lt
选择器。和*
选择器
$('div.parent>*:lt(2))
如果要包含文本节点,请执行.clone()
操作并删除不需要的内容,如下所示:
var children = $(".parent").clone();
children.find("ul").remove(); //or: children.find(":gt(1)").remove();
//children now contains everything by the <ul>
var children=$(“.parent”).clone();
children.find(“ul”).remove()//或:children.find(“:gt(1)”).remove();
//儿童现在包含
我在原始帖子中对海报示例标记中的节点做了一些评论。如果有人感兴趣,这里有一些东西可以打印出“真实”的结构。我刚刚在父元素中添加了一个
id
,以便在即将开始遍历DOM时更轻松地控制它:
<body>
<div id="parent" class="parent">
<div class="firstChild">firstChild</div>
SecondChild
<ul><li>thrid child</li></ul>
</div>
<script type="text/javascript">
(function (startNode) {
// Recursively walking the structure from the supplied node
function walk(node, indent) {
indent = (typeof indent==='undefined') ? '' : indent;
var children = node.childNodes;
var child, info;
// For each child of node...
for (var idx=0, len=children.length; idx<len; ++idx) {
child = children.item(idx);
// ..print it.
printNodeInfo(child, indent);
// If it was an element (tag) we try to display any children it might have
if (child.nodeType===1) {
arguments.callee(child, indentAdd+indent);
}
}
}
function printNodeInfo(node, indent) {
indent = (typeof indent==='undefined') ? '' : indent;
console.log(indent+getNodePrintString(node));
}
function getNodePrintString(node) {
var info = '';
// Check type and extract what info to display
if (node.nodeType===1) {info = node.nodeName;} // element nodes, show name
else if (node.nodeType===3) {info = trim(node.nodeValue);} // text nodes, show value
// If it was an empty textnode, return special string
if (!info) {return '[empty '+nodeTypes[node.nodeType]+' node]';}
else {return nodeTypes[node.nodeType]+': '+info+(node.id?'#'+node.id:'');}
}
// Just a utility function to trim values of textnodes
function trim(str) {
return str.replace(/^\s+/, '').replace(/\s+$/, '');
}
// Amount of indentation to add each level
var indentAdd = ' ';
// Mappings for nodeType => name of nodetype
var nodeTypes = {
1: '@Element'
, 2: '@Attribute' // not used right now
, 3: '@Text'
};
// Print info in start node
printNodeInfo(startNode);
// Start walking
walk(startNode, indentAdd);
})(document.getElementById('parent')); // Supply a start node
</script>
</body>
下面是如何获取元素的子节点,包括“纯”文本节点(文本不在标记内)
可能应该读取$(“.parent>:lt(2)”,以确保选择的节点位于父节点正下方。在这个例子中没有关系,但是如果firstchild有其他类似firstchild的内容,它将不会像预期的那样工作。是的,当然。我还意识到这不会选择文本节点。我错过了那个小细节。我从来没有发过这样的短信,老实说,我也不知道如果他们是那样的话,你可以选择他们。我确实遇到过这个问题,它似乎非常有用。实际上,类为“parent”的元素有5个子元素:1:一个空文本节点,2:类名为“firstChild”的div,3:值为“SecondChild”的textnode,4:
ul
,5:另一个空文本节点实际上,我们通常在“标记”上操作,像jQuery和Prototype这样的库可以方便地返回标签集合供我们操作。但是在这个范例中,上面的“父”元素只有两个子元素:div
和ul
。除非将文本节点“SecondChild”包装在类似span
之类的标记中,否则不会返回它。然后是“第二个孩子”和第三个孩子
@Element: DIV#parent
[empty @Text node]
@Element: DIV
@Text: firstChild
@Text: SecondChild
@Element: UL
@Element: LI
@Text: thrid child
[empty @Text node]
// Returns child nodes (including text nodes, if not empty) of 'node',
// but no more than 'limit' nodes.
// If limit given is not a number >= 0, it harvests as many as it can find.
function npupNodes(node, limit) {
// not a number or < 0 means 'no limit'
limit = (typeof limit!=='number' || limit<0) ? -1 : limit;
var result = [];
var children = node.childNodes;
var child, nodeType, captureCount=0;
// Loop over children...
for (var idx=0, len=children.length; idx<len && (limit<0 || captureCount<limit); ++idx) {
child = children.item(idx);
nodeType = child.nodeType;
// If it is an element or a textnode...
if (nodeType===1 || nodeType===3) {
if (nodeType===3 && !child.nodeValue.replace(/^\s+/, '').replace(/\s+$/, '')) {
// ..if it is a textnode that is logically empty, ignore it
continue;
}
// ..otherwise add it to the harvest, and increase counter
result.push(child);
captureCount += 1;
}
}
return result;
}
var someChildren = npupNodes(document.getElementsByClassName('parent')[0], 2);