[英]Simple GetElementById issue
I'm new to javascript I'm having a very simple problem. 我是javascript新手,遇到一个非常简单的问题。 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 我只想将一个类添加到
<div>
标记中,但是它不起作用
This is my javascript: 这是我的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 您接近了,方法
document.getElementById()
通过使用元素的ID返回HTML元素
HTML: HTML:
<html>
<body>
<div id="main">
This is my main content to be hidden
</div>
</body>
</html>
Javascript: 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: 如果要使用class属性选择元素而不是ID,则可以使用:
document.getElementsByClassName()
and then loop over the results 然后遍历结果
Here is a JSFiddle example: 这是一个JSFiddle示例:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.