Give each li element a tabindex, and add this CSS:
li:focus {
background: lightgreen;
}
<div class="items">
<ul>
<li tabindex="1">Item1</li>
<li tabindex="1">Item2</li>
<li tabindex="1">Item3</li>
<ul>
</div>
To do this in plain JavaScript:
- Add a click event listener to the
ul element.
- If the event's target is an
li element:
2a. If there's an existing li that's selected, remove its class.
2b. Add a selected class to the event's target.
document.querySelector('ul').addEventListener('click', function(e) { // 1.
var selected;
if(e.target.tagName === 'LI') { // 2.
selected= document.querySelector('li.selected'); // 2a.
if(selected) selected.className= ''; // "
e.target.className= 'selected'; // 2b.
}
});
.selected {
background: lightgreen;
}
<div class="items">
<ul>
<li>Item1</li>
<li>Item2</li>
<li>Item3</li>
<ul>
</div>
Note that LI must be capitalized in e.target.tagName === 'LI'.