1

how to target a li which is before/previous element of the selected or active li using css nth-child() concept?

<ul>
  <li><li>
  <li>i want to select this li</li>
  <li class="active"></li>
  <li><li>
</ul>
Saravana
  • 524
  • 1
  • 6
  • 28

1 Answers1

2

There is no previous sibling selector in CSS, there is a next adjacent sibling one though (using the + selector):

li.active {
  color: red;
}
li.active + li {
  color: green;
}
<ul>
  <li></li>
  <li>This one can't be selected with pure CSS only...</li>
  <li class="active">This is the active one</li>
  <li>This is adjacent to active</li>
</ul>

EDIT - Here's a jQuery way using prev() to select the immediately previous sibling:

$("li.active").prev().addClass("prevsibling");
li.active {
  color: red;
}
li.prevsibling, li.active + li {
  color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul>
  <li></li>
  <li>This one has had a class appended via jQuery!</li>
  <li class="active">This is the active one</li>
  <li>This is adjacent to active</li>
</ul>
David Wilkinson
  • 5,060
  • 1
  • 18
  • 32