0

I tried to find some way to solve my problem, which is to add class to the divs when I click on them, but I can't make it work.

var el = document.getElementsByClassName('applications');
var i;
for (i = 0; i < el.length; i++) {
  el[i].addEventListener("click", function() {
    if (el[i]) {
      el[i].className += el[i].className ? ' openDiv' : 'openDiv';
    }
  });
}

I have the 'for loop' because I used getElementsByClassName which gives a node list. I also created a codepen example:

http://codepen.io/anon/pen/dGqmMy

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252

1 Answers1

3

Instead of using complex string manipulation, use classList:

el[i].classList.add('openDiv');

I believe you might need to add a closure for the eventListeners to work.

So this would be considered as a solution:

var el = document.getElementsByClassName('applications');
var i;
for (i = 0; i < el.length; i++) {
  (function (i) {
    el[i].addEventListener("click", function() {
      if (el[i]) {
        el[i].classList.add('openDiv');
      }
    });
  })(i);
}
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
  • 1
    I don't think it anyway answers the problem... could be suggestion to make the existing code better... – Arun P Johny Feb 04 '16 at 11:06
  • @ArunPJohny I was... Okay.. I was suggesting the right way, because that might not work. I also said that using closures will work. But haven't provided the code. – Praveen Kumar Purushothaman Feb 04 '16 at 11:07
  • @PraveenKumar, I guess `if (el[i]) {` is not playing any role here, perhaps adding confusion.. – Rayon Feb 04 '16 at 11:24
  • @RayonDabre Yeah, one thing is, it looks like that person is actually checking whether that element exists or not. Good thing only right? – Praveen Kumar Purushothaman Feb 04 '16 at 11:25
  • If element does not exist, will `addEventListener` invoke handler ? _Note:_ `el.classList.contains('openDiv')` will needed as OP is trying to do toggle classes..I also feel, `forEach` would look pretty than `closure` ;) – Rayon Feb 04 '16 at 11:27
  • 1
    @RayonDabre Yeah, looks right... Let's see what's OP is upto. Should definitely come back if they have issues. So they will surely check the comments. Let's see. Thanks for the insights though! `:)` – Praveen Kumar Purushothaman Feb 04 '16 at 11:28