Change class of div on click


Seemingly simple question which is confusing me... all answers seem to be for JQuery only.

I am generating a table calendar with PHP.

enter image description here

Each day on the calendar is a tr > td > div which looks like this at the moment:

    <div class="" id="event" href="" onclick="this.className=\'selected\';return getDate({day});">

When a user clicks on one of the divs I want the background of that div to change its css class to 'selected'.

Then, if the user clicks another div I want that class to change to selected and the previous class to be removed so that only one div at any time can be 'selected'.

At the moment I am using this.className='selected which works except multiple divs can be selected!

How do get behaviour so that I can select a single div and highlight it, then if I decide to click another div, the previous div becomes de-selected and the new div is 'selected'?


Add an event listener to the div class via a loop, and add another class "selected" to the div if it is clicked. Otherwise, remove the "selected" class. The "selected" class will contain your css stuff.

For instance,

var x = document.getElementsByClassName('yourClass')
for (var i = 0; i < x.length; i++) {
    x[i].addEventListener("click", function(){

    var selectedEl = document.querySelector(".selected");

    }, false);;
By : codemax

In Standard javascript:

document.getElementById('foo').className += ' selected'

or in JQuery:


Your divs have same ID, which is wrong, do it like this

    <div class="event" href="">


with javascript:

    <div class="event" href="" onclick="selectMe(this);">

function selectMe(obj){
    var divs = document.getElementsByClassName("event");
    for(var i = 0; i < divs.length; i++)
       divs[i].className = "event";
    obj.className = "event selected"

This video can help you solving your question :)
By: admin