JQuery Get Class Name

I am trying to get the class name from a selection of images when clicked.

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

How can I get each value of an image class?

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');
+3
source share
2 answers

Try this instead:

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

Try:

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

The foregoing may, on reflection, not be exactly what you need. I 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'
});
+2
source

All Articles