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