2017-06-27 5 views
3

最後に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の最後のインスタンスを選択するにはどうすればよいですか? CSSで

jsfiddle

+0

可能な重複https://stackoverflow.com/questions/6401268/how-do:これは、トリックを行います-i-select-the-last-child-with-a-specific-class-in-css) –

+0

上記のリンク先の質問では、解決策は大きく異なります。リンクされた答えのソリューションは、私のユースケースには適用できません。以下の答えは私の問題に適用できる方法です。 –

答えて

2

いくつかの特定のルールがある場合を除き、それは厳しいものになります - それは常に最後から2番目だよう。要するに、あなたが求めているのは、存在しないlast-of-classのようなものです。 last-of-typeがありますが、要素タイプ(divpなど)にのみ適用され、クラスには適用されません。

次善策は、.form-group.has-errorクラスの最後の要素を取得するバニラ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>

それが修正される可能性がページに複数のフォームブロックの、これは有用なものにするには:

クラスを持つ最後の兄弟を選択

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>

+0

ニース!素晴らしい説明をありがとう。 –

+0

'forEach()'の代わりに 'for()'を使います。それは[もっと速く](https://jsperf.com/ktest23)で、IE11で動作します。 –

0

CSSだけでは達成できません。あなただけの持っている:

  • :last-child - 親でのこのタイプの最後の要素
  • ない最初の - 親
  • :last-of-typeの最後の子:selector ~ selector

あなたが持っているので.form-group Iブートストラップを使用していると仮定しているので、jQueryを使用しています。

$('section').each(function(){ 
    $('.has-errors', $(this)).last().css({borderBottom: '1px solid red'}) 
}) 
[?私はCSSで特定のクラス名を持つ「最後の子」を選択するにはどうすればよい](の
関連する問題