How to get the class name of the parent div

I have a checkbox in several nested divs. In my OnChangeevent, I want to get the class name of the parent div / container div pan-box placeholder.

The HTML structure is something like this

<div class="pan-box placeholder" producttype="I" price="34.99" data-productname="$34.99 Standard 15">
    <div class="pan-box-head col-md-12 no-pad">
        <div class="col-md-7 col-sm-12 no-pad pan-price">
        </div>
        <div class="col-md-5 col-sm-12 no-pad">
                <input type="button" value="View Details" class="viewbtn" onclick="CallOfferRenderAction('SP115','TWCv6')">
                <div class="phone">
                    <input type="checkbox" class="SelectedOffer" id="SP115" onchange="SaveCompairedOffers(this);">
                </div>
        </div>
    </div>
</div>

I tried the following code, but it returned the class name phone, which is the immediate parent of the flag. How can I get the first div class?

$(this).parent().prop('className');
+4
source share
2 answers

.parent() returns only the immediate parent.

You should use closest()instead:

$(this).closest('div.pan-box').prop('className');
+5
source

If I get you, you should do it like this:

$(function(){
    "use strict";

    $('.SelectedOffer').on('change', function() {
        console.log($(this).closest('.placeholder').attr('class'));
    });
});

See jsfiddle for details

0
source

All Articles