Home > Mobile >  Javascript to add class to last of class
Javascript to add class to last of class

Time:08-12

I have the following input and list:

<input id="myinput" type="text">

<ul id="mylist">
    <li ><a href="#">Link 1</a></li>
    <li ><a href="#">Link 2</a></li>
    <li ><a href="#">Link 3</a></li>
    <li ><a href="#">Link 4</a></li>
    <li ><a href="#">Link 5</a></li>
</ul>

with the following css to show/hide certain list items:

.display {
    display: block;
}
.hide {
    display: none;
}
.last {
    background-color: yellow;
}

I'm looking for javascript (preferably vanilla) to add last class to the LAST item with display class, so that I can highlight that item with CSS.

JSFiddle

Thanks!

CodePudding user response:

You can rely on Element.querySelectorAll to scan the element top to bottom up and down (DFS might be a better term). This makes the last node to be the last as you would define it. I found official documentation about it.

var nodes = document.querySelectorAll(".display");
var last = nodes[nodes.length - 1];
last.style.backgroundColor = "yellow"
<body>
  <input id="myinput" type="text">

  <ul id="mylist">
    <li ><a href="#">Link 1</a></li>
    <li ><a href="#">Link 2</a></li>
    <li ><a href="#">Link 3</a></li>
    <li ><a href="#">Link 4</a>
      <ul id="mylist2">
        <li ><a href="#">Link 1</a></li>
        <li ><a href="#">Link 2</a></li>
        <li ><a href="#">Link 3</a></li>
        <li ><a href="#">Link 4</a></li>
        <li ><a href="#">Link 5</a></li>
      </ul>
    </li>
    <li ><a href="#">Link 5</a></li>
  </ul>
</body>

  • Related