tags:

views:

65

answers:

4

Given this HTML:

<div id="flashcard-001" class="flashcard">
 <div class="question">What color is the sky?</div>
 <div class="answer">blue</div>
 <button class="show">Show</button>
 <button class="hide">Hide</button>
</div>

This works:

$("div")[1].innerHTML = "What color is an apple?";
$("div")[2].innerHTML = '<span style="font-size:48pt;color:red">red</span>';

And this works (both buttons turn red):

$("body div button").css('background-color', 'red');

So why doesn't this work (first button does not turn red as expected):

$("body div button")[0].css('background-color', 'red');
+2  A: 

When you specify [0] after a jQuery object you are accessing the direct DOM element, and DOM elements do not have a 'css' method defined ( reference ). The css method works on jQuery objects because it is defined in the jQuery.prototype and all jQuery objects inherit that method, which is why:

$('body').css('background', 'red')

Works, and $('body')[0].css will throw an error.

meder
+2  A: 

If you did:

$("body div button")[0].cssText = 'background-color', 'red';

That should work.

When you use [0] then you are looking at the DOM object, so at that point you can't use the jQuery helper functions but just go directly to the dom properties.

James Black
hmm, that doesn't work for me
Edward Tanguay
I think you mean `$("body div button")[0].cssText += 'background-color: red';`
Eric
Depends if he is replacing or appending to the css, but you could be right that it should be +=.
James Black
A: 

use instead:

$("body div button:first").css(...

see here

Scott Evernden
Who is downvoting this? It's perfectly valid answer.
SolutionYogi
omg downvoted for the being the first to supply the accepted answer!?? *eyeroll*
Scott Evernden
hmm odd. +1 as its correct!
redsquare
+3  A: 

As others already pointed out, when you use bracket syntax, you are accessing the actual DOM element not the jQuery object.

Try

$("body div button").eq(0).css('background-color', 'red');

or even better

$("body div button:first").css('background-color', 'red');
SolutionYogi
+1 for jQuery.eq; didn't know about it.
hasen j
both work nicely, thanks
Edward Tanguay