J. Jesper
J. Jesper

Reputation: 137

Add class to the clicked div with multiple divs with same class

How do I get the clicked div if the divs both got same class. For an example:

<div class="box"></div>  <div class="box"></div>

And I want to add another class to the div I click on.

New at JavaScript but I have figured out that I should use "this" in some way.

What I have done so far:

box = document.getElementById("box");
box.addEventListener("click, function(event) {
    event.target.classList.toggle("clicked");
}

But of course this only works for a div with an Id and not for multiple divs.

Upvotes: 0

Views: 2415

Answers (5)

palaѕн
palaѕн

Reputation: 73926

You can use document.querySelectorAll here like:

var boxes = document.querySelectorAll('.box');
Array.from(boxes).forEach(box => {
  box.addEventListener('click', function(e) {
    e.target.classList.toggle('clicked');
  });
});

Upvotes: 1

Keith
Keith

Reputation: 24211

If you attach the eventListener onto a containing element, here I've just used body, but more targeted selectors can give better performance.

You could then check the class of the item clicked.

Example below..

document.body.addEventListener("click", function (evt) {
  var el = evt.srcElement;
  if (el.classList.contains("box"))
    el.classList.toggle("clicked");
});
.clicked {
  background-color: yellow;
}
<div class="box">Box 1</div>  
<div class="notabox">Not a Box</div>  
<div class="box">Box 2</div>

Upvotes: 0

Rafael Odon
Rafael Odon

Reputation: 1360

If you want to keep using pure JavaScript without any additional lib, I believe Query Selectores should help you (https://developer.mozilla.org/pt-BR/docs/Web/API/Element/querySelectorAll).

Evolving your snippet:

document.querySelectorAll("box").forEach( function (){
    this.addEventListener('click', function(event) {
        event.target.classList.toggle("clicked");
    });
});

Upvotes: 0

Tomas Varga
Tomas Varga

Reputation: 1440

If you want to use document.getElementById() you need to add element the id attribute:

<div id="box1" class="box">

By design, ids are meant to be unique, so if you can assign each element an id, it shoud be enough.

I'd suggest an approach where you add the listener on a parent (or whole document) and check for the clicked element inside:

document.addEventListener('click', function (event) {
    if(event.target.classList.contains('box')) {
        event.target.classList.toggle('clicked');
    }
}

This approach is better performance-wise as it creates only one event handler, not a handler per element.

Upvotes: 0

alex
alex

Reputation: 644

with jquery

$('.box').click(function() {
  console.log($(this).text());
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="box">one</div><div class="box">two</div>

Upvotes: 0

Related Questions