[Javascript] Deep Search nested tag element in DOM tree

// For example you want to search for nested ul and ol in a DOM tree branch

// Give example <ol> <li> <ol> <li></li> </ol> </li> </ol> should retrun 2

function solution( tags = ['ul', 'ol']) {

  const [uls, ols] = tags.map(tag => Array.from($(`${tag}`)));
  const [logUl, logOl] = tags.map(tag => new Logger(`${tag}`));

  deepSearch(uls, 'ul', logUl);
  deepSearch(ols, 'ol', logOl);

  return logUl.count + logOl.count;
}

class Logger {
    constructor(tag) {
        this.tag = tag;
        this.num = 0;
    }
    
    get count () {
        return this.num;
    }
    
    get tagName () {
        return this.tag;
    }
    
    countOne() {
        this.num++;
    }
}

function deepSearch(els = [], tag = "", log) {
    
    // if no such elements passed in
    if (!els.length) {
        return;
    }
    
    log.countOne();
    
    // loop though the els and check whether contains tag
    els.forEach(el => {
        const targets = Array.from(el.getElementsByTagName(`${tag}`));
        if (targets.length) {
            deepSearch(targets, tag, log);
        }
    });
}
原文地址:https://www.cnblogs.com/Answer1215/p/9049101.html