Highlight elements inside a list once clicked

44 0 0 0

Last Updated : 2020-10-24 12:09:31

If you have let's say an unordered list and it is populated with multiple items and you need to highligh the clicked item and if clicked again remove the highlight. A very good and interresting way to do this is to make use of the buble behavoir for events and add event listener only for the parent container element, and then use the event.target to get to the clicked element itself, which is the list item in our example.

  • Here is the HTML
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
    <li>Item 4</li>
    <li>Item 5</li>

  • Here is the CSS
    ul {
    list-style: none;

    padding: 1rem;
    border: 1px solid #ccc;

    .highlight {
    background-color: cadetblue;
    color: #fff;

  • And here is the JS using the event.target
    const theList = document.querySelector('ul');
    theList.addEventListener('click', event => {
    event.target.closest('li').classList.toggle('highlight'); //This is ven better in case the li has multiple elements

Mohammed Anwar

Mohammed Anwar

Experienced technical lead PHP, MySQL and Laravel Developer for 15+ years, with proven ability to develop and create high-quality and optimized web applications. Great ability to build and optimize database design, schema and queries. Versed programing trainer and instructor delivering web courses and helping others to get into the field in a timely manner. Fast and eager learner for new technologies .