1

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!

user2840467
  • 801
  • 3
  • 10
  • 19

2 Answers2

2

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"; 
} 
Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130
  • In ES6 you should actually be able to `for (var elm of panel) { ... }` since NodeLists are supposed to be iterable as well. Not sure if browsers implement this though. – Felix Kling May 03 '16 at 16:42
  • @FelixKling If it is an iterable object then I would have suggested spread operator to OP. I think it is not yet supported. If we want to make nodeList objects to be iterated then we need to alter its prototype like `NodeList.prototype[Symbol.iterator] = Array.prototype[Symbol.iterator]` – Rajaprabhu Aravindasamy May 03 '16 at 16:44
2

document.getElementsByClassName returns a htmlCollection, not a single element. You can loop the elements to manipulate all of them

function slideUpClose(el) {
    var panels = document.getElementsByClassName(el);
    Array.prototype.forEach.call(panels, function(panel) {
        panel.style.transition = "top 0.5s ease-out 0s";    
        panel.style.top = "-1000px";    
    }    
}
baao
  • 71,625
  • 17
  • 143
  • 203
  • I haven't used getElementsByClassName before - just came across it when looking for alternative to Id - I should have realised the array creation with the plural of elements! – user2840467 May 03 '16 at 16:50