1

I have 5 divs which each need to perform the same function:

-collapse all divs -expand parent div

each element shares a class.

When I use getElementsByClass it returns a list of 5 items.

I try to use a for loop on the list but that doesn't work.

HTML:

<div class="parent">
    <div class="child"> x <div>
<div>
<div class="parent">
    <div class="child"> x <div>
<div>
<div class="parent">
    <div class="child"> x <div>
<div>

JS:

var child = getElementsByClassName("child");
var parent = getElementsByClassName("parent");
var i;
for(i=0; i<child.length; i++){
    i.onClick = function(){
        parent.style.height = "0";
        i.parentElement.style.height = "100px;
};
anon
  • 159
  • 2
  • 3
  • 9
  • 1
    @NageshSanika — They've got a closure … that's the cause of the problem. – Quentin Jul 18 '19 at 15:48
  • besides that your code is full of errors (HTML and JS!), i is just the incrementer of your for-loop, not a DOM node, try: `var children = document.getElementsByClassName('child'); Array.prototype.forEach.call(children, el => { el.addEventListener('click', (e) => { e.currentTarget.parentElement.style.height = "100px"; }); });` – exside Jul 18 '19 at 15:58
  • apart from the closure issue, `parent` is also an array. so ` parent.style.height = "0"` will not work. loop through the parent to set its height 0 – Sumith Jul 18 '19 at 16:13
  • found it https://stackoverflow.com/questions/4588759/how-do-you-set-a-javascript-onclick-event-to-a-class-with-css – anon Jul 18 '19 at 20:26

0 Answers0