Reputation: 10551
console.log($('.square').css('background-color')); // red
console.log($('.square')[1].css('background-color')); // error
console.log($('.square')[2].css('background-color')); // error
How can retrieve the green and blue square's attributes via jquery?
Upvotes: 1
Views: 36
Reputation: 288620
You should use eq
:
console.log($('.square').css('background-color'));
console.log($('.square').eq(1).css('background-color'));
console.log($('.square').eq(2).css('background-color'));
The problem is that css
is a method of jQuery objects. But if you use bracket notation to access individual elements, you get the "real" ones, without any jQuery wrapping.
Alternatively, you could:
Wrap it again in a jQuery object (expensive, not recommended):
$($('.square')[1])
Use vanilla-js to get the style:
$('.square')[1].style.backgroundColor; // Only to get inline styles
getComputedStyle($('.square')[1]).backgroundColor;
Upvotes: 4
Reputation: 10551
Another option appears to be this:
console.log($($('.square')[0]).css('background-color')); // red
console.log($($('.square')[1]).css('background-color')); // green (dark)
console.log($($('.square')[2]).css('background-color')); // blue
Upvotes: 0
Reputation: 38394
$($('.square')[1]).css('background-color')
The .css requires a jquery object, and the [1]
gives you a DOM object, so you must use $()
to convert it to jquery object (not sure if this is correct terminology)
Upvotes: 1
Reputation: 253476
Use eq()
:
console.log($('.square').eq(1).css('background-color'));
The square brackets retrieve the DOM node from the jQuery collection, not the jQuery object at that index point.
References:
eq()
.Upvotes: 3