【问题标题】:Select Last Nested Element选择最后一个嵌套元素
【发布时间】:2017-06-27 22:07:28
【问题描述】:

如何选择下面最后一个has-errors div?

<section class="form-block">
    <div class="form-group has-errors">
          ERROR!
    </div>
    <div class="form-group has-errors">
          ERROR!
    </div>
    <div class="form-group">
          stuff
    </div>
</section>

我可以选择第一个 has-errors 使用:

.form-block .form-group.has-errors:first-child {
  background-color: blue;
}

但是last-child 在上面不起作用。如何选择.form-group.has-errors 的最后一个实例?

jsfiddle

【问题讨论】:

标签: html css selector children


【解决方案1】:

使用 CSS 会很困难,除非有一些特定的规则——比如它总是倒数第二个。简而言之,您所要求的就像last-of-class,它不存在。有last-of-type,但仅适用于元素类型(divp 等),不适用于类。

下一个最佳选择是一些普通的 JS,用 .form-group.has-error 类抓取最后一个元素。

const hasErrors = document.querySelectorAll('.form-group.has-errors');
hasErrors[hasErrors.length -1].style.color = 'red';
<section class="form-block">
    <div class="form-group has-errors">
          ERROR!
    </div>
    <div class="form-group has-errors">
          ERROR!
    </div>
    <div class="form-group">
          stuff
    </div>
</section>

为了使它对页面上的多个表单块有用,可以修改为:

const formGroups = Array.from(document.querySelectorAll('.form-block'));


formGroups.forEach(function(block) {
  const hasErrors = block.querySelectorAll('.form-group.has-errors');
  hasErrors[hasErrors.length -1].style.color = 'red';
});
Form Block 1
<section class="form-block">
    <div class="form-group has-errors">
          ERROR!
    </div>
    <div class="form-group has-errors">
          ERROR!
    </div>
    <div class="form-group">
          stuff
    </div>
</section>

Form Block 2
<section class="form-block">
    <div class="form-group has-errors">
          ERROR!
    </div>
    <div class="form-group has-errors">
          ERROR!
    </div>
    <div class="form-group">
          stuff
    </div>
</section>

【讨论】:

  • 使用for() 而不是forEach()。它是a lot faster,适用于 IE11。
【解决方案2】:

抱歉,我在您的代码中看不到嵌套。

嵌套元素应该这样处理

<div class="form-group">
    stuff
    <div class="form-group">
        stuff
        <div class="form-group">
              stuff
        </div>
    </div>
</div>

这里没有我的问题的答案。 可能标题不准确

【讨论】:

    猜你喜欢
    • 2017-12-19
    • 2015-10-14
    • 2013-03-25
    • 2017-11-28
    • 1970-01-01
    • 2013-12-24
    • 2022-06-23
    • 2022-11-30
    • 2016-11-30
    相关资源
    最近更新 更多