多个最后一个孩子选择

时间:2014-04-14 02:44:14

标签: html css css-selectors

我想选择以下标签。这是否可以在不改变HTML结构的情况下实现? DIV.first元素是动态添加的,因此可能会发生变化。我需要在.first.bb之前的每个.first.a以及#wrapper中已经完成的最后一个设置样式。

http://jsfiddle.net/MqPLx/

HTML

<div id="wrapper">
    <div class="first">first</div>
    <div class="first bb">first second</div>
    <div class="first bb">first second</div>
    <div class="first bb">first second</div> <!-- <- need to select this -->
    <div class="first a">first</div>
    <div class="first a">first</div>
    <div class="first a">first</div>
    <div class="first bb">first second</div>
    <div class="first bb">first second</div>
    <div class="first bb">first second</div>
    <div class="first bb">first second</div> <!-- <- need to select this -->
    <div class="first a">first</div>
    <div class="first a">first</div>
    <div class="first a">first</div>
    <div class="first bb">first second</div> <!-- <- need to select this -->
</div>

CSS

 .first.bb:last-child {
    color:red;
}

 .first.bb + .first.a {
        color:red;
}

1 个答案:

答案 0 :(得分:0)

在询问时,以前的兄弟选择器位只能使用JavaScript完成 。见http://jsfiddle.net/iamnotsam/t4BUW/

// With jQuery
$('.bb + .a').prev().addClass('last-first-bb'); 

或使用纯JavaScript

// With just JavaScript
var elements = document.querySelectorAll('.bb + .a'),
    className = 'last-first-bb';

Array.prototype.forEach.call(elements, function(el, i){
  var el = el.previousElementSibling;
  if (el.classList)
    el.classList.add(className);
  else
    el.className += ' ' + className;
});

这样可以选择问题的棘手部分。使用CSS选择#wrapper的最后一个子项是微不足道的,所以我们不需要这些技巧。