Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery Get last from multiple class values

I have a couple of div's that look like this:

<div class="film cars-0317219"></div>
<div class="film wall-e-0910970"></div>
<div class="film finding-nemo-0266543"></div>
<div class="film cars-0317219"></div>

Im concerned with the second (so last) class name, but only of the divs that have the class 'film'. Is there any way I can get the last class name with JQuery?

To give you an example of what I want to do look below. I want to make these div's clickable and let the visitor go to /title/last-class-name.html

$('div.film').live('click', function(){

    // This returns the whole 'film random-title-id'
    // instead of just 'random-title-id'
    var id = $(this).attr('class');

    location.href = '/title/' + id + '.html';

});
like image 261
Bob Avatar asked May 08 '11 01:05

Bob


1 Answers

This should work:

$('div.film').live('click', function(){

    var classes=$(this).attr("class").split(" ");
    var id=classes[classes.length-1];

    location.href = '/title/' + id + '.html';

});

although if you don't already have IDs on your elements, this seems like it would make more sense as an ID.

like image 168
James Montagne Avatar answered Sep 19 '22 06:09

James Montagne