JS USES a for loop to iterate over child nodes to find elements

  • 2020-03-30 03:53:53
  • OfStack

This article mainly introduces JS to use a for loop with arrays to iterate over child nodes to find elements


function nextChildNode(node,clazz,tagName){ 
var count= node.childElementCount; 
for(var i=0;i<count;i++){ 
if(node==undefined || node.children[i]==undefined){ 
continue; 
} 
if(clazz){ 
if(node.children[i].getAttribute('class')==clazz){ 
return node.children[i]; 
} 
}else{ 
if(node.children[i].tagName==tagName){ 
return node.children[i]; 
} 
} 


} 
return null; 
} 

function getChildNode(node,classArg,tagNodeArg){ 
for(var i=0;i<classArg.length;i++){ 
node=nextChildNode(node,classArg[i]); 
} 
for(var i=0;i<tagNodeArg.length;i++){ 
node=nextChildNode(node,null,tagNodeArg[i]); 
} 
return node; 
} 

function getItemId(node){ 
var classNode=['itemInfo','itemDesc'],tagNode=['P','BUTTON']; 
node=getChildNode(node,classNode,tagNode); 
alert(node.getAttribute('itemid')); 

} 

# Call a function  
getItemId($(".shopItem")[0]); 

Related articles: