zoukankan      html  css  js  c++  java
  • [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);
            }
        });
    }
  • 相关阅读:
    用户场景分析
    人月神话阅读笔记03
    钢镚儿开发的最后一天
    钢镚儿开发的第九天
    4.25第10周周总结
    5号总结
    4号总结(3)
    4号总结(2)生成apk
    4号总结(1)
    3号寒假总结
  • 原文地址:https://www.cnblogs.com/Answer1215/p/9049101.html
Copyright © 2011-2022 走看看