[javascript] Cannot set property 'display' of undefined

I'm writting script to hide/show menu but I get some troubles.

    function displayMenu() {
//var classMenu = event.target.className;
//classMenu += 'Menu';
    //document.getElementsByClassName(classMenu).style.display = 'block';
document.getElementsByClassName('btn-pageMenu').style.display = 'block';
    }

In comment what I want to do finally, but even if I try with static var it's not working. In the CSS :

    fieldset.toolsbox ul.btn-pageMenu {display:none;}

I try like this too :

    .btn-pageMenu {display:none;}

No more success. Anybody have a suggestion ? I'm learning JS and I not finding errors when I compare with other similar scripts.

Thanks for your help :)

This question is related to javascript css

The answer is


document.getElementsByClassName('btn-pageMenu') delivers a nodeList. You should use: document.getElementsByClassName('btn-pageMenu')[0].style.display (if it's the first element from that list you want to change.

If you want to change style.display for all nodes loop through the list:

var elems = document.getElementsByClassName('btn-pageMenu');
for (var i=0;i<elems.length;i+=1){
  elems[i].style.display = 'block';
}

to be complete: if you use jquery it is as simple as:

?$('.btn-pageMenu').css('display'???????????????????????????,'block');??????

I've found this answer in the site https://plainjs.com/javascript/styles/set-and-get-css-styles-of-elements-53/.

In this code we add multiple styles in an element:

_x000D_
_x000D_
let_x000D_
    element = document.querySelector('span')_x000D_
  , cssStyle = (el, styles) => {_x000D_
      for (var property in styles) {_x000D_
          el.style[property] = styles[property];_x000D_
      }_x000D_
  }_x000D_
;_x000D_
_x000D_
cssStyle(element, { background:'tomato', color: 'white', padding: '0.5rem 1rem'});
_x000D_
span{_x000D_
font-family: sans-serif;_x000D_
color: #323232;_x000D_
background: #fff;_x000D_
}
_x000D_
<span>_x000D_
lorem ipsum_x000D_
</span>
_x000D_
_x000D_
_x000D_