14

I have got a CSS class like so:

.simpleClass {
    width: 25px;
}

And I have a matching element:

<div class="simpleClass"></div>

Can I add the property display: none; to the CSS class .simpleClass dynamically through jQuery? Thanks.

Jonathan Lam
  • 16,831
  • 17
  • 68
  • 94
Alex
  • 181
  • 2
  • 2
  • 5

6 Answers6

25

you can specify the style of the element by using .css like

$("div.simpleClass").css("width","25px");

have a look at jQuery.css()

Arthur Halma
  • 3,943
  • 3
  • 23
  • 44
Rafay
  • 30,950
  • 5
  • 68
  • 101
11

If I get it right, You don't want to give property to the instance element of simpleClass, but would like to give an extra property to the whole class ( covering all instances ) using JS.

In this case, You can use jQuery to append a style element to the head, giving You the opportunity to add additional CSS declarations.

However, I would not recommend this, because it causes Your code, and structure to get messy.

$("head").append("<style> .simpleClass{ display:none; } </style>");

This snippet will give extra display:none property to all .simpleClass elements existing in the time of doing this, and will also affect every later-inserted .simpleClass elements.

István Pálinkás
  • 2,217
  • 7
  • 25
  • 50
5
$('.simpleClass').css({display:'none'});
daryl
  • 14,307
  • 21
  • 67
  • 92
  • 1
    But this needs to be executed whenever a new element with simpleClass is added to the DOM. But there is no cross-browser way to do it (why does anyone even need this?). – Manuel Leuenberger Jul 16 '11 at 16:02
  • i'm running into an issue where i need elements to be hidden with display:none but i need to get their heights first. This is a legitimate ask! – Marcy Sutton May 14 '12 at 22:01
4

The property will be added to div if it already not exist in css class. Hence, it's always better to switch css class with new properties. Eg.

$( ".referenceClass" ).switchClass( "oldClass", "newClass");
domino_katrino
  • 356
  • 3
  • 19
3

The stylesheet is defined in a file, and you can't edit that with JavaScript. What you could do is this:

$(".simpleClass").live("domchanged", function() {
    $(this).css("display", "none");
});

But this is neither not cross-browser compatible nor efficient (nor tested by me ;). So I'd propose to use another predefined CSS class for this purpose. Why do you need something like this anyway?

Manuel Leuenberger
  • 2,327
  • 3
  • 21
  • 27
  • Thanx for ypur answer. But i have another way to solve my problem. My problem was slightly different and this way I would solve it. I have a table where I can select columns to display. Content loading with Ajax and I had to determine which columns are visible and what is not. I wanted to change the class property, and then add a class to a loaded content. But found another way. Sorry for my bad eanglish =) – Alex Jul 16 '11 at 16:26
2
$(document).ready(function(){
    $(.simpleClass).css('display','none');
});
Alex
  • 91
  • 1
  • 9