Jemes
Jemes

Reputation: 407

jQuery Get Class Name

I'm trying to get the class name from an selection of images when clicked.

The code below retrieves the first images class name but when I click on my other images with different class values they display the first images class.

How can I get each images class value?

HTML

<a href="#" title="{title}" class="bg"><img src="{image:url:small}" alt="{title}" class="{image:url:large}" /></a>

jQuery Code

    $(".bg").click(function(){
        var1 = $('.bg img').attr('class');

Upvotes: 4

Views: 22439

Answers (2)

fx_
fx_

Reputation: 1932

Try this instead:

$(".bg").click(function(){
    var1 = $(this).children('img').attr('class');

Upvotes: 7

David Thomas
David Thomas

Reputation: 253476

Try:

$(".bg").click(function(){
    var1 = $(this).attr('class');
});

The above might, on reflection, not be quite what you're after. I'd suggest trying:

$('.bg img').click(  // attaches the 'click' to the image
    function(){
        var1 = $(this).attr('class');
    });

Or:

$(".bg").click(function(){
    var1 = $(this).find('img').attr('class'); // finds the 'img' inside the 'a'
});

Upvotes: 3

Related Questions