js Method for getting the first level child element under an element of Recommendation

  • 2021-07-26 06:37:12
  • OfStack

js childnodes gets all the child elements, and we're actually getting the first-level child element.


function getChildren(obj){
  var objChild = [] ;
  var objs = obj.getElementsByTagName('*');
  for(var i=0,j=objs.length; i<j;++i){
    if(objs[i].nodeType != 1){alert(objs[i].nodeType);
      continue ;
    }
    var temp = objs[i].parentNode;
    if(temp.nodeType == 1){
      if(temp == obj){
        objChild[objChild.length] = objs[i] ;
      }
    }else if(temp.parentNode == obj){
      objChild[objChild.length] = objs[i] ;
    }
  }
  return objChild ;
}

Related articles: