I'm new to javascript I'm having a very simple problem. I just don't get what's going on.
I just want to add a class to a <div>
tag but it's not working
This is my javascript:
var element = document.getElementById("main");
element.classList.add("hidden");
Here's my fiddle:
You are close, the method document.getElementById()
returns an HTML element by using the id of the element
HTML:
<html>
<body>
<div id="main">
This is my main content to be hidden
</div>
</body>
</html>
Javascript:
var element = document.getElementById("main");
element.classList.add("hidden");
If you want to use the class attribute to select your elements rather than the id you can use:
document.getElementsByClassName()
and then loop over the results
Here is a JSFiddle example:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.