Emmet Arries
Emmet Arries

Reputation: 549

Why doesn't my JS add an HTML class?

I've been messing with this code for a while now, and I can't seem to make it work. I made a div that is a green box and I want it to do my CSS transform when it is clicked on (by using JS to add a class), however that is not what it is doing right now. What rookie mistake did I make with this one?


Here's my code: There is also a JSFiddle here!

function box() { document.getElementById('box')[0].setAttribute("class", "box_ready"); 
}
body {
    margin: 0;
    padding: 0;
}

.container {
    width: 800px;
    margin: 0 auto;
}

#box {
    width: 200px;
    height: 200px;
    background-color: #393;
}

#box:hover {
  cursor: pointer;
}

.box_ready {
    -webkit-animation: slide 2s;
            animation: slide 2s;
            animation-fill-mode: forwards;
}

@keyframes slide {
  to {
    -webkit-transform: translate(600px, 0px);
        -ms-transform: translate(600px, 0px);
            transform: translate(600px, 0px);
            transform: rotateY(90deg);
	}
  
}

/* Add WebKit when done*/
<div class="container">
<div id="box" onclick="box()"></div>
</div>

Upvotes: 0

Views: 102

Answers (4)

zfj3ub94rf576hc4eegm
zfj3ub94rf576hc4eegm

Reputation: 1273

I was able to get it to work by removing the [0] from your function:

function box(){
    document.getElementById('box').setAttribute("class", "box_ready"); 
}

Remember, getElementById() returns one element, but getElementsByClassName() returns an array of elements.

Also, although this may be obvious, you can only use getElementById() when the element has that as an ID. Ditto with getElementByClassName().

Upvotes: 3

PitaJ
PitaJ

Reputation: 15002

You are removing the existing class when you set the class HTML attribute. This removes the existing box class styling which makes the box disappear. You are also overriding the translate transform with the second transform CSS property.

Fixed JSfiddle: https://jsfiddle.net/zn2nhbnt/20/

Edit: notice, I changed the translate and removed the prefixed properties for clarity.

Upvotes: 3

Vignesh Subramanian
Vignesh Subramanian

Reputation: 7289

it is not getElementsById it should be getElementById

Upvotes: 1

Malitta N
Malitta N

Reputation: 3423

Your code should change to

document.getElementById('box').setAttribute("class", "box_ready");

getElementById returns only a single matching element, not an array, since a single document can not have an ID repeating more than once, according to HTML standards.

Upvotes: 2

Related Questions