Highlight elements inside a list once clicked

943 0 0 0

Last Updated : 2024-04-28 19:27:56

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
    <ul>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
    <li>Item 4</li>
    <li>Item 5</li>
    </ul>?

    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 .