How do I make this loop all children recursively?

前端 未结 10 576
情书的邮戳
情书的邮戳 2020-12-24 12:06

I have the following:

for (var i = 0; i < children.length; i++){
   if(hasClass(children[i], \"lbExclude\")){
       children[i].parentNode.removeChild(ch         


        
相关标签:
10条回答
  • 2020-12-24 12:50

    The most clear-cut way to do it in modern browsers or with babel is this. Say you have an HTML node $node whose children you want to recurse over.

    Array.prototype.forEach.call($node.querySelectorAll("*"), function(node) {
      doSomethingWith(node);
    });
    

    The querySelectorAll('*') on any DOM node would give you all the child nodes of the element in a NodeList. NodeList is an array-like object, so you can use the Array.prototype.forEach.call to iterate over this list, processing each child one-by-one within the callback.

    0 讨论(0)
  • 2020-12-24 12:54

    if items are being created in a loop you should leave a index via id="" data-name or some thing. You can then index them directly which will be faster for most functions such as (!-F). Works pretty well for 1024 bits x 100 items depending on what your doing.

    if ( document.getElementById( cid ) ) {
     return;
    } else {
      what you actually want
    }
    

    this will be faster in most cases once the items have already been loaded. only scrub the page on reload or secure domain transfers / logins / cors any else and your doing some thing twice.

    0 讨论(0)
  • 2020-12-24 12:54

    If you use a js library it's as simple as this:

    $('.lbExclude').remove();
    

    Otherwise if you want to acquire all elements under a node you can collect them all natively:

    var nodes = node.getElementsByTagName('*');
    for (var i = 0; i < nodes.length; i++) {
      var n = nodes[i];
      if (hasClass(n, 'lbExclude')) {
        node.parentNode.removeChild(node);
      }
    }
    
    0 讨论(0)
  • 2020-12-24 12:57

    Normally you'd have a function that could be called recursively on all nodes. It really depends on what you want to do to the children. If you simply want to gather all descendants, then element.getElementsByTagName may be a better option.

    var all = node.getElementsByTagName('*');
    
    for (var i = -1, l = all.length; ++i < l;) {
        removeTest(all[i]);
    }
    
    0 讨论(0)
提交回复
热议问题