0

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');

4 Answers 4

2

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/

Sign up to request clarification or add additional context in comments.

Comments

2

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');

Comments

2

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.

6 Comments

I do not want to use this piece of code, I don't know why but it is not working on IE
@aliA It should work on IE, if it doesn't work then you are doing something wrong.
Yes, jQuery 1.9 and below support IE and :last selector works in those browsers, however, as you know jQuery 2+ doesn't support IE8 and below.
@PSL jQuery doesn't depend on the browser's built-in selector support, it does it all by itself. This is one of the ways you get better cross-browser behavior when using jQuery.
@Barmar @:undefined Thanks, that's what i guessed. Anyways probably this is a different issue.
|
1

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! :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.