JavaScript: Getting the second level parent of an element

From The Travis van der Font Wiki
Jump to: navigation, search
Using jQuery:
$('#example_d').click(function ()
{
    var element = $(this).parent().parent().find('.example_class_name');
    
    console.log(element);
})
Using jQuery and the pure DOM instead of repeatedly attaching the parent to the jQuery object:
jQuery.fn.getParent = function(count)
{
    var last = this[0];

    for (var i = 0; i < count; i++)
    {
        last = last.parentNode;
    }

    return jQuery(last);
};

// example usage:
$('.example_class_name').getParent(3);