Selecting the Previous Sibling of an Element

For the same reason CSS cannot reach the parent element if a given selector, you also are not able to reach the element appearing directly before a given element in HTML with CSS. It’s easy to select the element directly following any element with + *, but there’s no way to go backward.

In JavaScript there is previousSibling which returns the previous node, which could also be a text node or comment node (not always what we expect) so what we’re usually looking for is the element that’s equal to the previousElementSibling of another element.

Parts Required

JS Tests

Using the previousElementSibling of the selected element:

element.previousElementSibling

Plugins Capable

Syntax Examples

EQCSS

@element [type=button] {
  $prev {
    background: gold;
  }
}

Selectory

[test="this == document.querySelector(`#known`).previousElementSibling"] {
  background: lime
}

XPathy

/* All previous siblings */
[xpath="//*[@id='target']/preceding-sibling::*"] {
  background: red;
}

/* First previous sibling */
[xpath="//*[@id='target']/preceding-sibling::*[1]"] {
  background: lime;
}

Demos