-2

I'm trying to make a menu, but when I have tried to execute the code in Chrome I've got an error.

So for debug proposes I made a button:

<input type="button" style="position: fixed; left:0; bottom:0; width:50px; height:25px;" value="test" onclick="login('logf')" />

This is the function where error is:

var loginshow = false;


function login(c)
{
    e = document.getElementsByClassName(c);
    if(loginshow)
    {
        e.style.height = "0";
    }
    else
    {
        e.style.height = "110px";
    }
    loginshow=!loginshow;

}

The error from google chrome:

bar.js:13 Uncaught TypeError: Cannot set property 'height' of undefined
    at login (bar.js:13)
    at HTMLInputElement.onclick ((index):32)
  • 3
    `getElementsByClassName` returns an array – Weedoze Apr 14 '17 at 12:54
  • Which tool do you use to develope your application ? If you wish you can type debugger; just before your javascript code and when you browse your application, on the google chrome, you can press the key F12 to open the source view and debug your code. The code debugger; will be hit. And you can see, may be there is an error with the class name etc.. – Coskun Ozogul Apr 14 '17 at 13:02
  • @Weedoze is correct, `e` is an array, so you need to iterate over the array of elements, or if you know there is only one, refer to it as `e[0].style.height` – Mikkel Jan 24 '18 at 23:04
  • Possible duplicate of: [Trying to get element by className doesn't seem to be working](https://stackoverflow.com/q/28631930) – Makyen Jan 27 '18 at 23:55
  • Possible duplicate of [What do querySelectorAll, getElementsByClassName and other getElementsBy\* methods return?](https://stackoverflow.com/questions/10693845/what-do-queryselectorall-getelementsbyclassname-and-other-getelementsby-method) – Makyen Jan 27 '18 at 23:55

1 Answers1

1

getElementsByClassName returns an array-like object of all child elements which have all of the given class names. You need to iterate all the elements and apply the style on each one

var loginshow = false;


function login(c) {
  let elements = document.getElementsByClassName(c);
  for(let i=0,l=elements.length;i<l;i++){
    elements[i].style.height = loginshow ? "0" : "110px";
  }
  loginshow = !loginshow;

}
div {
  background-color: tomato;
  border: 1px solid black;
}
<input type="button" style="position: fixed; left:0; bottom:0; width:50px; height:25px;" value="test" onclick="login('logf')" />

<div class="logf"></div>
<div class="logf"></div>
Weedoze
  • 13,683
  • 1
  • 33
  • 63