Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Get Class Name

Tags:

jquery

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');
like image 412
Jemes Avatar asked Dec 27 '22 23:12

Jemes


2 Answers

Try this instead:

$(".bg").click(function(){
    var1 = $(this).children('img').attr('class');
like image 69
fx_ Avatar answered Jan 06 '23 03:01

fx_


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'
});
like image 22
David Thomas Avatar answered Jan 06 '23 02:01

David Thomas