2

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.

4 Answers 4

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';
Sign up to request clarification or add additional context in comments.

1 Comment

Nice downvoting spree.
2
document.getElementsByClassName('ads')[0].style.display ='none';

1 Comment

Or loop over the returned list if you want to change all of them.
2

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.

1 Comment

Note that none needs to be wrapped in quotes.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.