'document.getElements and ejs files [duplicate]

I noticed the document.getElements is not working for ejs files. as in below code, I need to display: none the div class="delegate".

myscripts.js

document.getElementsByClassName("delegate").style.display="none";

index.ejs

<div class="delegate"> 

<p>helooo</p>
</div>

the error message shows in browser: Cannot set properties of undefined (setting 'display')

can you please help me to understand.



Solution 1:[1]

You're selecting a collection of nodes (actually an HTMLCollection) but trying to treat them as a single item. The collection doesn't have a display property, hence the error message.

You'll need to loop through them all and set the style individually. One way to do this is to convert the array-like HTMLCollection to an array first (using Array.from, or the spread opertor [...]) and then use Array.forEach to update each item:

[...document.getElementsByClassName("delegate")].forEach(el => el.style.display='none')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1