Yousuf Daramay
Yousuf Daramay

Reputation: 127

How to hide a certain class in JavaScript

I don't know why this is not working. I am trying to hide a certain class and this is the only line of code I have on Javascript:

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

For some reason I get the error:

"document" is not defined.

What does that mean, it's not a variable.

Please help and thank you.

Upvotes: 1

Views: 43

Answers (1)

P.S.
P.S.

Reputation: 16412

getElementsByClassName method returns ALL elements with the same class, think of it as an array of elements with the same class. So you need to specify, which element do you want to hide. In my example, I have only one element with such class, so I'm selecting it like the first element of an array ([0]). Your code should look like this:

document.getElementsByClassName("popular")[0].style.display = "none";

console.log('Current "display" property value is: ' + document.getElementsByClassName("popular")[0].style.display)
<div class="popular">TARGET</div>

Upvotes: 2

Related Questions