tags:

views:

70

answers:

2

Hi everyone, I have a div with Class. For example

<div class="button check"></div>.The css is defined for both 'button','check'. I want to access the above div through jquery and write something in the div.I tried with

$('.button check').html("sample data");

I do not see anything being written when I run the page.

Please help me.

+6  A: 

Just chain the CSS classes together, separated by periods:

$('.button.check').html("sample data");

You will also see better performance in some browsers, by specifying the tag name as well:

$('div.button.check').html("sample data");

Update: After reading Brian's answer, I re-read the original question I realized you might be under the impression you need to use both to reference the div. If you had:

<div class="button cancel">Cancel</div>
<div class="button check">Check</div>

Then chaining selectors (i.e. .button.cancel) would make sense. However, if it was the only div on the page or you wanted all the divs with button class, you don't need both classes:

<div class="button check">Check</div>

This would select it fine:

$('div.check').html("sample data");
Doug Neiner
+1, too fast for me .., and you can also do `$('.check.button')` the order of the classes is not important .. (*as a note to the OP*)
Gaby
@Gaby... haha, I always feel lucky when that happens... I am sure you will get me on another question :)
Doug Neiner
Additionally, ID routed selectors always perform faster.$("#header .button.check") for instance.
BBonifield
Thanks everyone for the quick responses.It did work with $('.button.check').Could somebody please explain why i need another period before check?
Its because each `class` on an element is treated separately. In fact, it might make more sense to you if you viewed `class="one two"` as `classes="one two"` Each one is independent of the other. So, when you want to select a single element using two, you have to chain them together (they both start with a period). If you had an `id`, you would also chain those... only the id starts with `#`: `#myDiv.button.check` -- Though you would rarely if ever use that last selector.. it was just an example.
Doug Neiner
Thanks for explaining Doug.
@user269527 Without the period (.) it is a element like div, span etc not a class.
Mark Schultheiss
+1  A: 

Hey,

Can you just target one class, do you need both? You can do one class like:

$("div.button")

OR

$(".button")

For multiple classes, it could be:

$(".button, .check")

OR:

$(".button").add(".check")

HTH.

Brian
@Brian +1 for depth of understanding! I totally missed the possibility that the OP thought both classes were necessary. Nice answer, though the last two examples are a little confusing given the context of a single element presented by the OP.
Doug Neiner
True, good point.
Brian