Marcelo Assis
Marcelo Assis

Reputation: 5194

Selecting a parent element (without using Jquery)

I just need to access the parent div where I have a button changing his siblings divs. A code example can explain better:

<div class="parent">  <!-- This is structure repeats N times -->
    <div class="divToToggleVisiblity divA">trololo A</div>
    <div class="divToToggleVisiblity divB">trololo B</div>
    <button onClick="toggleThem(this)">This button will toggle above divs</button>
</div>


function toggleThem(a){  // something like this, BUT without Jquery
    $(a).closest(".parent").find(".divA").hide();
}

Upvotes: 4

Views: 3666

Answers (2)

Samuel Liew
Samuel Liew

Reputation: 79032

function toggleThem(elem) {
    elem.parentNode.getElementsByClassName('divA')[0].style.display = 'none';
}

Upvotes: 2

Joseph Silber
Joseph Silber

Reputation: 219938

That's what parentNode is for:

a.parentNode.querySelectorAll('.divA');

Upvotes: 8

Related Questions