【问题标题】:Get element's inherited (cascaded) ancestor CSS classes using Javascipt使用 Javascript 获取元素的继承(级联)祖先 CSS 类
【发布时间】:2020-08-16 17:01:44
【问题描述】:

window.onload = function() {
    var elements = document.querySelectorAll('body *');
    for (var i = 0; i < elements.length; i++) {
        elements[i].addEventListener("click", function(e) {
            console.log(e.target.className + "->" + e.target.parentNode.className);
        });
    }
};
.outer_box_green{
  border-style:solid;
  border-color:green;
}
.inner_box_thick{
  margin:2px;
  padding:3px;
  border-style:dashed;
  border-width:4px;

}
.line_1{
  font-size:2em;
  display:block;
}
.line_2{
  font-size:4em;
}
  <body>
    <div class="outer_box_green">
      <div class="inner_box_thick another_inner_box_class">
        <span class="line_1">Line 1</span>
        <span class="line_2">Line 2</span>
        <div>Line 3</div>
      </div>
    </div>
  </body>

使用 vanilla Javascript,我们如何获取被点击元素的类以及被点击元素嵌套在其中的“祖先”元素的所有类。例如,如果我们有

<div class="outer_box_green">
  <div class="inner_box_thick another_inner_box_class">
    <span class="line_1">Line 1</span>
    <span class="line_2">Line 2</span>
    <div>Line 3</div>
  </div>
</div>

期望的行为是在单击元素时获取包含祖先类的 Javascript 数组:

  • “第 1 行”被单击
    • ["line_1", "inner_box_thick", "another_inner_box_class", "outer_box_green"]
  • “第 2 行”被单击
    • ["line_2", "inner_box_thick", "another_inner_box_class", "outer_box_green"]
  • “第 3 行”被单击
    • ["inner_box_thick", "another_inner_box_class", "outer_box_green"]

我想出了如何使用parentNode.className 打印类,但它只上升了一级(参见 sn-p)。如何一次获取所有嵌套 HTML 祖先的所有 CSS 类?

【问题讨论】:

    标签: javascript html css parent ancestor


    【解决方案1】:

    您可以向上移动 DOM 树,直到 parentNode 变为 null

    window.onload = function() {
      var elements = document.querySelectorAll('body *');
      for (let i = 0; i < elements.length; i++) {
        elements[i].addEventListener("click", function(e) {
          const classNames = [];
          let node = e.target;
          while(node != null){
            if(node.className) classNames.push(node.className);
            node = node.parentNode;
          }
          console.log(...classNames);
        });
      }
    };
    .outer_box_green {
      border-style: solid;
      border-color: green;
    }
    
    .inner_box_thick {
      margin: 2px;
      padding: 3px;
      border-style: dashed;
      border-width: 4px;
    }
    
    .line_1 {
      font-size: 2em;
      display: block;
    }
    
    .line_2 {
      font-size: 4em;
    }
    <div class="outer_box_green">
      <div class="inner_box_thick another_inner_box_class">
        <span class="line_1">Line 1</span>
        <span class="line_2">Line 2</span>
        <div>Line 3</div>
      </div>
    </div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-17
      相关资源
      最近更新 更多