Dan Lee
Dan Lee

Reputation: 704

How do you select parent of parent div in javascript?

I have a custom accordion setup using Javascript. Currently using onclick I'm toggling a style to the parent div (currently holding a class of "card" and adding "card-open"). My question is how to I go one div higher and begin manipulating the div with the class "time-steam-event"?

Live Example: http://bit.ly/1rr6zGA

HTML:

<div class="time-stream-event" id="{entry_id}">
    <div style="background: url({timeline_item_img}) no-repeat center center;" class="event-bg grayscale"></div>
    <div class="card">
        <h3><a href="{title_permalink="/timeline"}">{title}</a></h3>
        <div class="event-year">{timeline_item_date format="%F %Y"}</div>
        <a href="#" class="togglelink"></a>
        <div class="toggle-box">
            <p>{timeline_item_description}</p>
            <div class="employees">Number of Employees</div>
            <div class="employee-count-no"> <i class="ss-icon">&#x1F465;</i> {timeline_item_employees}</div>
        </div>
        <div class="open-arrow"></div>
    </div>
</div>

Javascript:

$.fn.slideFadeToggle  = function(speed, easing, callback) {
    return this.animate({opacity: 'toggle', height: 'toggle'}, speed, easing, callback);
};

$('.toggle-box').hide();

$('a.togglelink').on('click', function (e) {
    e.preventDefault();
    var elem = $(this).next('.toggle-box')
    $('.toggle-box').not(elem).hide();
    elem.slideFadeToggle();

    var parent_div = $(this).parent().toggleClass('card-open');

});

Upvotes: 0

Views: 117

Answers (4)

Lasitha Benaragama
Lasitha Benaragama

Reputation: 2209

document.getElementsByClassName("togglelink")[0].parentElement;

Thats how it doing using Javascript.

 document.getElementsByClassName("togglelink")

return the array of element which have "togglelink" class. You need to get the the Exact Element. If you have only one element My code is just fine.

Upvotes: 1

nrsharma
nrsharma

Reputation: 2562

If your div is at the 2nd position in hierarchy (by level) you can use

var yourdiv = $(this).parent().parent();

Or you can use .closest() either

var yourdiv = $(this).closest('.time-steam-event');

Upvotes: 0

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62488

you can get like this:

var parent_div = $(this).parent().parent();

or:

var parent_div = $(this).parent().closest(".time-steam-event");

Upvotes: 0

Milind Anantwar
Milind Anantwar

Reputation: 82231

You can use .closest() or .parents():

var obj= $(this).closest('.time-steam-event');//reference to closest .time-steam-event

or

var obj= $(this).parents('.time-steam-event');//reference to closest .time-steam-event

Upvotes: 0

Related Questions