Pars
Pars

Reputation: 5262

How to get css value of an element inside array?

I have a list, and want to get the value of background of the last element.

    <ul>
        <li style="background: red;"></li>
        <li style="background: blue;"></li>
        <li style="background: yellow;"></li>
        <li style="background: white;"></li>
    </ul>

and I use this jQuery script

var color = $( 'ul li' ).get(-1).css('background');

but it's not working. I googled it, but nothing found.
Could any one help me to find out the problem.

EDITED: this is not working on IE, my be I am wrong. but isn't any other way?

$( 'ul li:last' ).css('background');

Upvotes: 0

Views: 507

Answers (4)

Arius
Arius

Reputation: 1387

All answers above will propably output empty string.

Please check:

var color = $('ul li').eq(-1).css('background-color');

In fact, you are seting the background-color, no background itself.

JsFiddle to prove: http://jsfiddle.net/7gxkp/

Upvotes: 2

PSL
PSL

Reputation: 123739

You can do:

 var color = $( 'ul li:last' ).css('background');

Reason is get(-1) returns DOM element which doesn't have css method, css is a method of jquery object and not Native DOM element.

or do :

var color = $( 'ul li' ).get(-1).style.background;

You can also use jquery .last()

 var color = $( 'ul li' ).last().css('background');

Note that jquery css uses getComputerStyle so you may end up getting all the background properties of the element (defaulted by the user agent as well) not just the color. If you want just the color using jquery css then you may want to specify .css('background-color') explicitly.

Upvotes: 2

Jason P
Jason P

Reputation: 27022

The reason your code doesn't work is because get() returns the DOM node, which doesn't have a css() function. You're looking for this:

$( 'ul li' ).eq(-1).css('background');

Upvotes: 2

blackeyebeefhorsefly
blackeyebeefhorsefly

Reputation: 1949

I'm not sure on the usage of get, but you can use CSS selectors with your jquery to do it like

var color = $( 'ul li:last-child' ).css('background');

It should be simpler! Let me know if this works for you! :)

Upvotes: 1

Related Questions