admin管理员组文章数量:1287828
I am doing a school project and it's my first time using JS, and we are not allowed to use any ID's for css styling, but on some event that the user does I want to change the style of a div
in the page:
HTML:
<div class="ads">
...
</div>
CSS:
.ads{
display:block;
//and some other style properties
}
and when the user do the event I want to change the display property into :
display : none;
I know how it can be done using ID for the element, but how can it be done only by a class name?
I would like to be able to do it something like this:
document.getElementsByClassName('ads').style.display=none;
Thank you.
I am doing a school project and it's my first time using JS, and we are not allowed to use any ID's for css styling, but on some event that the user does I want to change the style of a div
in the page:
HTML:
<div class="ads">
...
</div>
CSS:
.ads{
display:block;
//and some other style properties
}
and when the user do the event I want to change the display property into :
display : none;
I know how it can be done using ID for the element, but how can it be done only by a class name?
I would like to be able to do it something like this:
document.getElementsByClassName('ads').style.display=none;
Thank you.
Share Improve this question asked Aug 18, 2017 at 14:38 user8244016user8244016 1,0193 gold badges14 silver badges26 bronze badges4 Answers
Reset to default 3If you know that there is only one element with that class, use the first element of the NodeList
that document.getElementsByClassName
returns:
document.getElementsByClassName('ads')[0].style.display = 'none';
document.getElementsByClassName('ads')[0].style.display ='none';
If you have just a one element with class"ads"
, you can use:
document.querySelector('.ads').style.display='none'
Else, if you have more than one element you can add a unique class name for you element like this
<div class="ads foo">
and using document.querySelector('.foo').style.display='none'
for changing it's style.
You should put index, also the string after the equal sign must be with quotation marks, like below:
document.getElementsByClassName('ads')[0].style.display="none";
w3schools
The NodeList object represents a collection of nodes. The nodes can be accessed by index numbers. The index starts at 0.
本文标签:
版权声明:本文标题:javascript - How to change a style property of element by class name without any use of ID's in JS? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741304921a2371310.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论