Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DOM not updating after adding a class to a div?

I'm trying to write a program that collects all class names in a div, stores them in an array and pushes them all back to the DOM with a class called blue at the end, this is the HTML:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>some title</title>
  <style>
    .blue{
        width: 200px;
        height: 200px;
        background: blue;
    }
  </style>
</head>
<body>

    <div class="someClass otherClass" id="box"></div>
    <button id="btn">click</button>

</body>
</html>

The thing is, I know how to get all the class names inside the div and even how to push blue (on btn click) inside of that div together with the other values I have collected but why isn't the blue box showing up? What am I missing?

var domManipulation = function(){
      var box = document.querySelector('#box');
      var btn = document.querySelector('#btn');
      var class_list = [];

      if(box.classList.length > 0){
        for(var i = 0; i < box.classList.length; i++){
          class_list.push(box.classList[i]);
        }
      }

      btn.addEventListener('click', function(){
          class_list.push("blue");
          box.classList.add(class_list);
          console.log(class_list);
      });

 }();

Here is a JsBin and I can't use jQuery btw.

like image 211
Student Avatar asked Jan 02 '16 18:01

Student


1 Answers

This is the problem:

box.classList.add(class_list);

You can't add a whole array of classes because they end up being comma-separated.

var domManipulation = function() {
  var box = document.querySelector('#box');
  var btn = document.querySelector('#btn');
  var class_list = [];

  if (box.classList.length > 0) {
    for (var i = 0; i < box.classList.length; i++) {
      class_list.push(box.classList[i]);
    }
  }

  btn.addEventListener('click', function() {
    class_list.push("blue");
    class_list.forEach(function(e){
      box.classList.add(e);
    })
    console.log(class_list);
  });

}();
#box {height: 50px; background: #eee}
#box.blue {background: blue}
<div class="someClass otherClass" id="box"></div>
<button id="btn">click</button>
like image 86
Shomz Avatar answered Sep 21 '22 13:09

Shomz