Jennifer Anthony
Jennifer Anthony

Reputation: 2277

Getting class name of last child element

I want to retrieve the class name of the last child element in .find_class, but my code gives me undefined. How can I fix it?

Example: http://jsfiddle.net/gBxan/

<div class="find_class">
    <div class="class1"></div>
    <div class="class2"></div>
    <div class="class3"></div> <!-- I want to get this div's class name -->
</div>

var find = $('div.find_class div:last').find('div:last').attr('class');
alert(find);

Upvotes: 2

Views: 1205

Answers (3)

drch
drch

Reputation: 3070

Your example in the question is slightly different than your example in the replies. You only want to be looking at the immediate child divs.

Try this:

var find = $('div.find_class > div:last').attr('class');
alert(find);

See http://jsfiddle.net/VbxpY/

Upvotes: 0

Krasimir
Krasimir

Reputation: 13529

maybe the following code will do the job:

var divs = $(".find_class").find("div");
var lastDiv = divs.eq(divs.length-1);
alert(lastDiv.attr("class"));

Upvotes: 0

Jon
Jon

Reputation: 437336

You need to lose the extra find:

var cls = $('div.find_class div:last').attr('class');

See it in action.

Upvotes: 11

Related Questions