...">

Why it doesn't work: $ ("body div button") [0] .css

With this HTML in mind:

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

      

It 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 (the first button won't turn red as expected):

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

      

+2


source to share


4 answers


As noted, when you use the parenthesis 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');

      

+3


source


When you specify [0] after a jQuery object, you are accessing the direct DOM element, and the DOM elements do not have a specific css ( link ) method . The css method works with jQuery objects since it is defined in jQuery.prototype and all jQuery objects inherit this method, so:

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



Works and $ ('body') [0] .css throws an error.

+2


source


If you did this:

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

      

This should work.

When you use [0] you are looking at the DOM object, so at this point you cannot use the jQuery helper functions, you just go directly to the dom properties.

+2


source


use instead:

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

      

see here

0


source







All Articles