Search code examples
javascripthtmlappendchild

appendChild is slow


Javascript:

var wrapper = document.getElementById("wrapper");
var div = document.createElement("div");
wrapper.appendChild(div);
div.className += " red"; // this should happened after appendChild()

CSS:

div{color:blue; transition: all 2s;}
div.red{color:red;}

What I want:

Assigning a "red" class to div, should make nice color animation. I want to append a div, then assign a class, so it will animate.

What i got instead:

Div is already appended red, with no animation going on.

Is there any workaround?


Solution

  • Have you tried using css animations instead?

    I would suggest something like this:

    JSBIN

    // css

    div {
      animation: toRed 2s ease-out;
      animation-fill-mode: forwards;
       width: 200px; height: 200px;
    }
    
    @keyframes toRed {
        0%      { background-color: blue; }
        100%    { background-color: red; }
    }
    

    // javascript

    var wrapper = document.getElementById("wrapper");
    var div = document.createElement("div");
    wrapper.appendChild(div);
    

    This way you don't necessarily need to keep track of an extra class.