最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Getting class name of last child element - Stack Overflow

programmeradmin6浏览0评论

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: /

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

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/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);
Share edited Oct 7, 2011 at 18:46 vzwick 11.1k5 gold badges46 silver badges63 bronze badges asked Oct 7, 2011 at 18:15 Jennifer AnthonyJennifer Anthony 2,27710 gold badges38 silver badges56 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 11

You need to lose the extra find:

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

See it in action.

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

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/VbxpY/

发布评论

评论列表(0)

  1. 暂无评论