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 badges
Add a ment  | 

4 Answers 4

Reset to default 3

If 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.

本文标签: