0

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

1
  • Welcome to Stack Overflow. Same. There is no immediate difference. jQuery is a Framework for JavaScript. So either is fine. Commented Mar 26, 2020 at 1:45

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

OK thanks, I wasn't sure if I should be branching off into jQuery or not. Maybe I'll just stick with vanilla for now until I get it down better. Thanks again for your time and advice.
0

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/

1 Comment

Thanks for the link, I didn't even think about a multi selection, good information there.
0

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

1 Comment

I see never really thought about doing it that way, I not sure why. Maybe I was just to focused on learning jQuery to thing of doing it with vanilla. Thanks you for your answer

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.