user2840467 user2840467 - 7 months ago 23
HTML Question

document.getElementsByClassName not working like getElementById

I have this code (running on www.dtwdev.co.uk/errors/index.html)

which is basically the following:

<script>
function slideUpClose(el) {
var panel = document.getElementsByClassName(el);
panel.style.transition = "top 0.5s ease-out 0s";
panel.style.top = "-1000px";
}
</script>


with a little styling

<style>
#selection {background:#f1f1f1; width:600px; height:300px;}
</style>


and the HTML:

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


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

Basically document.getElementsByClassName would return a nodeList.

var panel = document.getElementsByClassName(el);
Array.from(panel).forEach(function(elm){
 elm.style.transition = "top 0.5s ease-out 0s";    
 elm.style.top = "-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].style.top = "-1000px"; 
}