Matija Matija - 2 months ago 5
CSS Question

Select class but apply style only to one clicked element

For example I have this code

<div class="year">
<div class="month" id="month-1"></div>
<div class="month" id="month-2"></div>
<div class="month" id="month-3"></div>
<div class="month" id="month-4"></div>
<div class="month" id="month-5"></div>
<div class="month" id="month-6"></div>
<div class="month" id="month-7"></div>
<div class="month" id="month-8"></div>
<div class="month" id="month-9"></div>
<div class="month" id="month-10"></div>
<div class="month" id="month-11"></div>
<div class="month" id="month-12"></div>
</div>

<script>
document.querySelector(".month").addEventListener("click",function (){
//here I need to add some code
}
</script>


In place where "I need to add some code", I want to write something like this
make color only of clicked element blue

But if I use

this.style.color="blue"


it will add that style to all div.month.

For example if I clicked on element with ID
month-1
, I only want that particular element to change color.

**ALL ANSWERS ARE CORRECT!! HOW I CAN SELECT ALL OF THEM TO BE CORECT? **

Answer

Like Titus said the querySelector returns only the first element that matches, we use getElementsByClassName if want to get all elements that match the class name. And we loop through the returned collections to bind the listener.

var Months = document.getElementsByClassName("month");

for (var i = 0; i < Months.length; i++) {
    Months[i].addEventListener('click', function() { this.style.color = "#ff0000"; }, false);
}
.month { height: 30px; }
<div class="year">
<div class="month" id="month-1">1</div>
<div class="month" id="month-2">2</div>
<div class="month" id="month-3">3</div>
<div class="month" id="month-4">4</div>
<div class="month" id="month-5">5</div>
<div class="month" id="month-6">6</div>
<div class="month" id="month-7">7</div>
<div class="month" id="month-8">8</div>
<div class="month" id="month-9">9</div>
<div class="month" id="month-10">10</div>
<div class="month" id="month-11">11</div>
<div class="month" id="month-12">12</div>
</div>

Comments