zl程序教程

您现在的位置是:首页 >  前端

当前栏目

[Javascript] Deep Search nested tag element in DOM tree

JavaScript in Tree dom Element search Deep TAG
2023-09-14 08:59:17 时间
// 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);
        }
    });
}