1

i need help :) I have a Div, and in this Div are many other Div's with a Class. And i need to change only the last Div's Class inside the Div:

    <div id='main'>

    <div class='inside'></div>
    <div class='inside'></div>
    <div class='inside'></div>    <- Only this to be changed?

    </div>

I have a jQuery function that searches for every div inside the main Div:

    $('#main').find('.inside').each(function() {

    alert($(this).attr('class'));

    });

This does work but when i try to change only the last Divs Class it changes the Classes of all Divs inside the main Div. Is it possible to change only the last inside class Div?

Thanks!

Thorsten
  • 215
  • 1
  • 2
  • 13
  • possible duplicate of [How do I select the last element with a specified class from descendants of this?](http://stackoverflow.com/questions/8323096/how-do-i-select-the-last-element-with-a-specified-class-from-descendants-of-this) – Felix Kling Feb 05 '13 at 14:49

2 Answers2

1

You can use .last:

$('#main .inside').last().addClass(....);

The jQuery documentation is quite extensive and spending a little time to read through it is worthwhile.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
0

To change css use .css

$('#main .inside:last').css('width','100');
Anton
  • 32,245
  • 5
  • 44
  • 54
  • Thanks! Sory but i forget to say that i need to change the CSS of the last div. Is that Possible too? – Thorsten Feb 05 '13 at 14:49
  • Updated, is that what you wanted? – Anton Feb 05 '13 at 14:50
  • Ok, i tried the CSS one but this does not work. Do you know why? – Thorsten Feb 05 '13 at 14:53
  • I have no Console to check^^ But i wrote it the same way you did, are you sure that this is right? Thanks :) – Thorsten Feb 05 '13 at 14:54
  • Yea it works for me :s what css property are you trying to add to the div? – Anton Feb 05 '13 at 14:56
  • If i do alert($('#main .inside:last')); i get [object Object], but the CSS does not change. – Thorsten Feb 05 '13 at 14:57
  • I tried: $('#main .inside:last').css('opacity','0'); But this does not work. Do you know why? – Thorsten Feb 05 '13 at 14:59
  • There is nothing wrong with that part of the code, there must be something else in your code that is the problem http://jsfiddle.net/j8SW8/1/ – Anton Feb 05 '13 at 15:00
  • @Anton: Don't use `attr('class','test')` because it removes all other classes from the element, use `addClass()` instead. – Mottie Feb 05 '13 at 15:02
  • Took it away since the question wasnt how to add class it was css – Anton Feb 05 '13 at 15:05
  • Thank You really much Anton, now it works :) Can you please tell me another thing? Now i need to know the last Divs horizontal position. Do you know how this works? Thanks :) – Thorsten Feb 05 '13 at 15:05
  • You can use .position().top so $('#main .inside:last').position().top – Anton Feb 05 '13 at 15:07