简体   繁体   English

选择上一个嵌套元素

[英]Select Last Nested Element

How do I select the last has-errors div below? 如何选择下面的最后一个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>

I can select the first has-errors using: 我可以使用以下方法选择第一个has-errors

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

But last-child does not work above. 但是, last-child不能胜任。 How do I select the last instance of .form-group.has-errors ? 如何选择.form-group.has-errors的最后一个实例?

jsfiddle 的jsfiddle

With CSS it will be tough unless there are some specific rules - like it's always the 2nd from last. 除非有一些特定的规则,否则使用CSS会很困难 - 比如它始终是最后的第二个。 In short what you're asking for is like last-of-class , which doesn't exist. 简而言之,你所要求的就像last-of-class ,不存在。 There is last-of-type but that only applies to element type ( div , p , etc), not to classes. last-of-type但只适用于元素类型( divp等),而不适用于类。

The next best option is some vanilla JS to grab the last element with the .form-group.has-error class. 下一个最好的选择是使用.form-group.has-error类来获取最后一个元素的vanilla JS。

 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> 

To make this useful for multiple form blocks on a page it could be modified to: 为了使它对页面上的多个表单块有用,可以将其修改为:

 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> 

Sorry, I can't see nesting in your code. 对不起,我在代码中看不到嵌套。

Nested elements should be disposed like this 嵌套元素应该像这样处理

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

no answer to my problem here. 这里没有回答我的问题。 maybe the title not to be exact 也许标题不准确

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM