简体   繁体   中英

Simple GetElementById issue

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:

http://jsfiddle.net/72o6j6r0/

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:

http://jsfiddle.net/mko3uf9f/

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM