Javascript 在节点列表中查找节点
我有这样一个节点列表: [text,div.post,comment,text,div.post,comment,text,div.post,comment,text,div.post,comment,text,div.post,comment,text,comment,text,div.post,comment,text] 这个节点列表是ajax调用的结果,div.post是我的帖子,我想选择它来添加新的类名Javascript 在节点列表中查找节点,javascript,nodelist,Javascript,Nodelist,我有这样一个节点列表: [text,div.post,comment,text,div.post,comment,text,div.post,comment,text,div.post,comment,text,div.post,comment,text,comment,text,div.post,comment,text] 这个节点列表是ajax调用的结果,div.post是我的帖子,我想选择它来添加新的类名 如何使用vanilla javascript从该节点列表中选择div.post?只需
如何使用vanilla javascript从该节点列表中选择div.post?只需迭代并添加类即可。因为不能按原样循环,所以可以使用Array.forEach和Function.call 在这里:
要浏览并找到所有匹配条件,您必须像Amit的答案那样进行循环。否则,上面的解决方案将适用于cherry拾取它。像itmars和Amit Jokis一样,答案在for循环中
nodelist = [text, div.post, comment, text, div.post, comment, text, div.post, comment, text, div.post, comment, text, div.post, comment, text];
for(var i=0; i< nodelist.length;i++){
var nodeItem = nodelist.item(i);
if(nodeItem.nodeName=="div" && (nodeItem.className.indexOf("post") > -1)){
//do your stuff
}
}
您可以编写选择器查找器。这不太具体,但肯定需要改进。您可以通过类id和标记名找到选择器。它将从节点列表返回第一个节点 演示 var children=document.getElementById'foo'.childNodes; 找到并打印“酒吧”,孩子们; 查找并打印“divbaz”,儿童; 函数findPrintSelector,节点列表{ 打印'>>Found?:'+JSON.stringifytoElgetNodeBySelectornodeList,选择器; } 函数printstr{ document.getElementById'out'.innerHTML+=str+; } 函数getNodeBySelectornodeList,选择器{ 变量部分=选择器。拆分/?=[\.]/g; 对于变量i=0;i
nodelist = [text, div.post, comment, text, div.post, comment, text, div.post, comment, text, div.post, comment, text, div.post, comment, text];
youritem = nodelist.item(1);
nodelist = [text, div.post, comment, text, div.post, comment, text, div.post, comment, text, div.post, comment, text, div.post, comment, text];
for(var i=0; i< nodelist.length;i++){
var nodeItem = nodelist.item(i);
if(nodeItem.nodeName=="div" && (nodeItem.className.indexOf("post") > -1)){
//do your stuff
}
}