0

So I have this menu constructed with <ul> element

<ul>
  <li class="item">
    <a>Item 1</a>
  </li>
  <li class="item">
    <a>Item 2</a>
  </li>
  <li class="item">
    <a>Item 3</a>
  </li>
  <li class="item mobile-item">
    <a>Item 4</a>
  </li>
</ul>

The menu would look look something like this

Item 1 / Item 2 / Item 3

with the last element hidden with the class .mobile-item

On mobile the menu turns into an accordion then only the .mobile-item shows up

My problem now is the outcome is:

Item 1 / Item 2 / Item 3 /

The last class item has border on its right

How would I target the last item class without the .mobile-item in its class list

Joshua
  • 1
  • 1

2 Answers2

1

Using :nth-last-child(2) works in this case where you seem to want the second-to-last child:

li.item:nth-last-child(2) {
  color: red;
}
  
<ul>
  <li class="item">
    <a>Item 1</a>
  </li>
  <li class="item">
    <a>Item 2</a>
  </li>
  <li class="item">
    <a>Item 3</a>
  </li>
  <li class="item mobile-item">
    <a>Item 4</a>
  </li>
</ul>
Rob Moll
  • 3,345
  • 2
  • 9
  • 15
  • I tried this, BUT another thing I want to add is the menu consists of this multiple `
      ` which consists of different counts of `
    • ` and some might not have the `mobile-item` class for example a ul with only `li.item`
    – Joshua Aug 02 '21 at 11:30
  • @Joshua how does this solution depend on the `mobile-item` class? What wouldn't work with only `li.item`? – Jere Aug 02 '21 at 11:35
  • @Jere the `item` class `mobile-item` only gets shown on mobile size. the Solution rob presented affects those `ul` with only 2 `li` child – Joshua Aug 02 '21 at 11:44
  • 1
    '_the Solution rob presented affects those ul with only 2 li child_' That is not correct. Please see [this](https://www.w3schools.com/cssref/tryit.asp?filename=trycss3_nth-last-child) – Rob Moll Aug 02 '21 at 12:00
0

You can use jQuery for this problem. I got inspiration for this answer from this post. With the following solution you could target the item before the item with the .mobile-item class. This selects the .mobile-item then the previous li and adds the class .highlight.

$('.mobile-item').prev('li').addClass('highlight')
.highlight {
  color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
  <li class="item">
    <a>Item 1</a>
  </li>
  <li class="item">
    <a>Item 2</a>
  </li>
  <li class="item">
    <a>Item 3</a>
  </li>
  <li class="item mobile-item">
    <a>Item 4</a>
  </li>
</ul>
Extensus
  • 44
  • 1
  • 5