user2840467 user2840467 - 2 years ago 82
HTML Question

document.getElementsByClassName not working like getElementById

I have this code (running on

which is basically the following:

function slideUpClose(el) {
var panel = document.getElementsByClassName(el); = "top 0.5s ease-out 0s"; = "-1000px";

with a little styling

#selection {background:#f1f1f1; width:600px; height:300px;}

and the HTML:

<div id="selection" class="slideUp">Content heading
<button class="close_button" id="close_this_content_panel" onclick="slideUpClose('slideUp')">Click to close</button>
<p>Some content goes here</p>

What I'm looking for is for when the button is clicked, the content panel should slide up and out of the window. I've managed to get this working with document.getElementById but am having trouble making it work for class names. Would appreciate any advice!

Answer Source

Basically document.getElementsByClassName would return a nodeList.

var panel = document.getElementsByClassName(el);
Array.from(panel).forEach(function(elm){ = "top 0.5s ease-out 0s"; = "-1000px"; 

You have to iterate over each elements to set its style/attribute. Use Array.from(nodeList) to convert the nodeList to a native array object. Then use its forEach function to iterate over each elements.

If your environment doesn't support ES6 then use the below code,

var panel = document.getElementsByClassName(el);
for(var i=0,len=panel.length;i<len;i++){
  panel[i].style.transition = "top 0.5s ease-out 0s";    
  panel[i] = "-1000px"; 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download