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);
            }
        });
    }
  • 相关阅读:
    线程原理 创建方式
    Chapter17 【异常、线程】
    驱动
    java中Super到底是什么意思
    Java 8后的首个长期支持版本Java 11
    OpenJDK和JDK区别
    异常
    模拟斗地主洗牌发牌
    Debug追踪
    Python 垃圾回收机制详细
  • 原文地址:https://www.cnblogs.com/Answer1215/p/9049101.html
Copyright © 2011-2022 走看看