Sakthivel
Sakthivel

Reputation: 666

How can the jQuery code for initialization be simplified?

At first, while page loading, I am suppressing some of the elements visibility. Based on the function clicked, then, each of the element will displayed. My aim is to simplify the below code while page load. Any idea?

$("span[class='user-name']").css("display", "none");
$("span[class='password']").css("display", "none");
$("span[class='urlcontent']").css("display", "none");
$("span[class='email']").css("display", "none");
$("#About").css("display", "none");
$("#Careers").css("display", "none");

Upvotes: 0

Views: 61

Answers (4)

Mohamed-Yousef
Mohamed-Yousef

Reputation: 24001

you can merge your Ids and classes in just one line and display them to none the next code will apply for all your span elements So if you want to specify spans use span[[class='user-name']]

 $('span,#About,#Careers').css("display", "none");

or you can hide all of them by using .hide()

$('span,#About,#Careers').hide(); 

Upvotes: 0

deitch
deitch

Reputation: 14581

I have a class "hidden", which has display: none; in CSS, which I apply to everything that should be hidden and only dynamically be shown:

.hidden {
  display: none;
}

And then in my HTML I add that class:

<span class="password hidden">...</span>

So I only need to do something when I want to show it:

$("span.password").show();

or

$("span.password").removeClass("hidden");

Also, you do not need to do [class=password]. Just use the proper jQuery/Sizzle selector for class:

$("span.password")
$("span.email")

etc.

Upvotes: 0

Balachandran
Balachandran

Reputation: 9637

jQuery

Note that you can have multiple selectors separated by commas in a query.

$(".user-name,.password,.urlcontent,.email,#About,#Careers").hide();

CSS

You can also hide the elements by simply using CSS.

.user-name, .password, .urlcontent, .email, #About, #Careers {
    display: none;
}

Upvotes: 0

astroanu
astroanu

Reputation: 3971

add a class to the elements you need to hide

<span class="user-name hide"></span>

and hide them on dom ready

$('.hide').hide();

or just use css

.hide{display:none;}

I think this method is more cleaner because changing class names or adding replacing them later on will not mess up your functionality.

Upvotes: 2

Related Questions