0

I would like to select following tags. Is this possible without changing HTML structure ? DIV.first elements are added dynamically so they may change. I need to style each last .first.bb before .first.a and the last one in #wrapper which is already done.

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;
}
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
user2537093
  • 139
  • 2
  • 9
  • Unfortunately according http://stackoverflow.com/questions/1817792/css-previous-sibling-selector and http://stackoverflow.com/questions/9742590/last-child-selector-with-classname?rq=1 I don't believe there is a good answer to this. – Daniel Paul Apr 14 '14 at 03:17
  • There is no good CSS-only answer. The only real answer is to select with JavaScript, see below. – iamnotsam Apr 14 '14 at 04:04

1 Answers1

0

The previous sibling selector bit can only be done with JavaScript at the time of the asking. See http://jsfiddle.net/iamnotsam/t4BUW/

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

Or with plain 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;
});

This does the selecting for the tricky portion of your question. Selecting the last child of #wrapper with CSS is trivial, so we don't need tricks for that.

iamnotsam
  • 9,470
  • 7
  • 33
  • 30