Starkers
Starkers

Reputation: 10551

Retrieve certain element with class via an index

http://jsfiddle.net/9G6NM/

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

Answers (4)

Oriol
Oriol

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

Starkers
Starkers

Reputation: 10551

Another option appears to be this:

http://jsfiddle.net/9G6NM/1/

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

AaronLS
AaronLS

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)

http://jsfiddle.net/9G6NM/2/

Upvotes: 1

David Thomas
David Thomas

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:

Upvotes: 3

Related Questions