Fero
Fero

Reputation: 13315

How to get class name of second parent using jQuery

When I click on the expand image, I need to get the class name of the second parent.

For example if I click the expand image in the first div, I need to get the class name test-one-heading.

If I click on the second div, I need to get the class name test-two-heading

<div class="content">
<div class="left-activity-block test-one-heading">
<div class="clearfix leftsidebar-title  title-active"> 
<h2>TEST 1</h2>
<div style="cursor: pointer;" class="collapse-symbol filter-plus-symbol"><img width="12" height="12" title="" alt="" src="/sites/all/themes/images/icons/expand.png"></div>
</div>
</div>

<div class="content">
<div class="left-activity-block test-two-heading">
<div class="clearfix leftsidebar-title  title-active"> 
<h2>TEST 2</h2>
<div style="cursor: pointer;" class="collapse-symbol filter-plus-symbol"><img width="12" height="12" title="" alt="" src="/sites/all/themes/images/icons/expand.png"></div>
</div>
</div>

How can I do this using jQuery?

Upvotes: 1

Views: 10657

Answers (4)

Vivek Viswanathan
Vivek Viswanathan

Reputation: 1963

You can associate click event to the image and on click you may use:

$(this).closest(".left-activity-block").attr("class");

You would get both the class names and you can filter the one you require.

Upvotes: 3

user997287
user997287

Reputation: 163

Try this:

var secondParentName = $("myElement").parent().parent().attr("class");

Upvotes: 1

James Jithin
James Jithin

Reputation: 10565

What about this code?

$(document).ready(

function() {
    $("img").click(

    function() {
        alert($($(this).parents("div")[2]).attr('class').split(/\s+/)[1]);
    });
}

);

Upvotes: 0

mu is too short
mu is too short

Reputation: 434635

All you have to do is go back up the DOM from the image, stop when you find .left-activity-block, grab all the classes on that element, and find the one that isn't left-activity-block:

$('img').click(function() {
    var div     = $(this).closest('.left-activity-block')[0];
    var classes = div.className.split(/\s/);
    for(var i = 0; i < classes.length; ++i)
        if(classes[i] != 'left-activity-block')
            alert(classes[i]);
});

Demo: http://jsfiddle.net/ambiguous/GkpkE/

Upvotes: 0

Related Questions