Previous Selector Mixin

This JavaScript function lets you define a CSS selector list and apply a CSS rule to the previous sibling node of any matching tags in your document.

Syntax

prev(selector, rule)

Example

Input:

prev('li:nth-of-type(2)', 'background: lime;')

Output:

/* li:prev */
[data-prev-unique="0"] {
  background: lime;
}

Code


function prev(selector, rule) {

  var tag = document.querySelectorAll(selector)
  var style = ''
  var count = 0

  for (var i = 0; i < tag.length; i++) {

    var attr = selector.replace(/\W+/g, '')

    tag[i].previousElementSibling.setAttribute('data-prev-' + attr, count)

    style += '\n/* ' + selector + ':prev */\n'
             + '[data-prev-' + attr + '="' + count + '"] {\n'
             + '  ' + rule + '\n'
             + '}\n'

    count++

  }

  return style

}

Techniques Capable