Stephen Little
Stephen Little

Reputation: 5

hiding elements with javascript vs jquery

I was wondering about hiding elements with DOM, the person in the course is doing this by setting the display to none

document.getElementById("id-name-1").style.display = "none";
document.getElementById("id-name-2").style.display="none";

We are hiding two elements here, now both elements have the same class. I have been converting what the course is showing me into jQuery as well for added challenge. The jQuery code that I used is as follows, the name of the class they both has is say dice.

$(".dice").hide();

This hides both elements at the same time, which way would be better? I know that if I had other elements with class dice it would also hide them. So maybe that is why the other way is better? Thank you for your thoughts -- I am new to this.

Stephen

Upvotes: 0

Views: 169

Answers (3)

Oscar Velandia
Oscar Velandia

Reputation: 1166

If you use vanilla javascript, can do something like

document.getElementsByClassName('className').forEach(el => el.style.display = "none")

I recommend you use vanilla javascript instead of JQuery because is most probably that you will use javascript than jquery in a new project. and on the other hand, will be more easy for you use libraries like react if you have a good vanilla javascript foundation.

Upvotes: 1

TOLULOPE ADETULA
TOLULOPE ADETULA

Reputation: 788

Document.querySelectorAll(".dice") would also be able to the above based on the style using purely javascript. So it all comes down to preference since it works the same way with display:none;. Also,.hide() takes in optional arguments/callback functions which can help with hiding the element(s).

Upvotes: 0

Twisty
Twisty

Reputation: 30893

Your question is open ended. No right or wrong answer.

$(".dice").hide();

As mentioned, this will hide all elements with Class "dice". If you want to be more specific, you can be:

$("#id-name-1", "#id-name-2").hide();

This selector uses IDs and selects both elements.

Your selector can be more vague or more precise as needed.

See More: https://api.jquery.com/category/selectors/basic-css-selectors/

Upvotes: 0

Related Questions