简体   繁体   中英

Why does my function return undefined when calling document.getElementsByClassName?

Im trying to create a simple switch using css/JavaScript. In the following you can see that im calling

document.getElementsByClassName('onOffSwitch').style.animation = 'off';

jsBin

What other code is needed for js to understand im talking about the div named 'onOffSwitch'? Was wondering why this current codeset doesn't work and how to fix it.

getElementsByClassName() returns collection. Specify index like the following.

document.getElementsByClassName('onOffSwitch')[0].style.animation = 'off';

Because .getElementsByClassName() returns a live node list (collection) of elements and you are trying to style the collection, rather than one element within the collection:

// Change the animation style of the first element with the class "onOffSwitch"
document.getElementsByClassName('onOffSwitch')[0].style.animation = 'off';

Also, because .getElementsByClassName() returns a "live" node list (a list that is updated every time you use the variable assigned to the list), it can really hinder performance. In most cases, a static node list is better and you can get that with:

document.querySelectorAll(".onOffSwitch");

But, the same rules apply. That's an entire collection. You'll need to access individual elements within the collection to work with their properties.

Now, looking at your code, you don't really want a collection at all. You only have the one div class="onOffSwitch" , so you could just get that one element with:

document.querySelector("div.onOffSwitch");

And then you could work with it directly.

 let state = { switchG: 'On', bits: [0,1,0,1] }; // Get reference to the div var divSwitch = document.querySelector('div.onOffSwitch'); // Set up event handler divSwitch.addEventListener("click", flipSwitch); function flipSwitch() { if (state.switchG == 'On'){ state.switchG = 'Off'; console.log(state.switchG); divSwitch.style.animation = 'off 1s 1'; } else { state.switchG = 'On'; console.log(state.switchG); divSwitch.style.animation = 'on 1s 1'; } } 
 .onOffSwitch{ background-color: #4dc71f; border-radius: 5px; position: absolute; left: 40%; height: 20px; width: 55px; overflow: hidden; text-align: center; cursor:pointer; } @keyframes off { 0%{ background-color: green; } 100%{ background-color: red; } } @keyframes on { 0%{ background-color: red; } 100%{ background-color: green; } } 
 <div class = 'onOffSwitch'>On</div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM