Saturday, June 1, 2024
 Popular · Latest · Hot · Upcoming
42
rated 0 times [  43] [ 1]  / answers: 1 / hits: 43472  / 11 Years ago, tue, march 12, 2013, 12:00:00

In javascript is there an easy way to target the parent of a parent?



I'm using this.parentNode as the element of a function to select the parent, and I tried both this.parent.parentNode and this.parentNode.parentNode, but both simply return the direct parent.

I'm trying to affect the div surrounding the div surrounding the 'this'. I did manage to make it work using a simple loop statement that repeats the parentNode selection twice, but I assume there's a better way.


More From » parent

 Answers
67

this.parentNode.parentNode is correct, you must (with apologies!) have had a mistake in the test where you tried it.



Example: Live Copy | Source



HTML:



<div id=outermost>Outermost
<div id=inner1>Inner 1
<div id=inner2>Inner 2</div>
</div>
</div>


JavaScript:



var inner2 = document.getElementById(inner2);

display(inner2.id = + inner2.id);
display(inner2.parentNode.id = + inner2.parentNode.id);
display(inner2.parentNode.parentNode.id = + inner2.parentNode.parentNode.id);

display(Try clicking the blue 'inner2' above);

inner2.onclick = function(e) {
display(Click: this.id = + this.id);
if (this.parentNode) {
display(Click: this.parentNode.id = + this.parentNode.id);
if (this.parentNode.parentNode) {
display(Click: this.parentNode.parentNode.id = + this.parentNode.parentNode.id);
}
}
};

function display(msg) {
var p = document.createElement('p');
p.innerHTML = String(msg);
document.body.appendChild(p);
}


Output (assuming one clicks as directed):



inner2.id = inner2
inner2.parentNode.id = inner1
inner2.parentNode.parentNode.id = outermost
Try clicking the blue 'inner2' above
Click: e.target.id = inner2
Click: e.target.parentNode.id = inner1
Click: e.target.parentNode.parentNode.id = outermost

[#79639] Monday, March 11, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kileyr

Total Points: 112
Total Questions: 105
Total Answers: 114

Location: United States Minor Outlying Island
Member since Sat, May 28, 2022
2 Years ago
;