I feel this should be an easy problem, but alas I find myself stuck. What I'm trying to do is set up a way so that every time you click on a cell on a table(or anywhere), it displays the parentNode of each element, essentially traversing up the DOM tree. I figured I would need to use elem.parentNode, but I'm stuck on the traversing part. Any gurus out there that can help me out, it would be greatly appreciated.
I feel this should be an easy problem, but alas I find myself stuck. What I'm trying to do is set up a way so that every time you click on a cell on a table(or anywhere), it displays the parentNode of each element, essentially traversing up the DOM tree. I figured I would need to use elem.parentNode, but I'm stuck on the traversing part. Any gurus out there that can help me out, it would be greatly appreciated.
Share Improve this question asked Jan 31, 2011 at 18:03 NinjaCodeNinjaCode 791 gold badge2 silver badges8 bronze badges2 Answers
Reset to default 11var element; //your clicked element
while(element.parentNode) {
//display, log or do what you want with element
element = element.parentNode;
}
var tables = document.getElementsByTagName('table');
for (var i=0,len=tables.length;i<len;++i){
tables[i].onclick = function(evt){
if (!evt) evt = window.event;
var element = evt.target || evt.srcElement;
while (element){
console.log(element);
element = element.parentNode;
}
};
}
If you really want clicking on any element everywhere, then simply:
document.body.onclick = function(evt){
if (!evt) evt = window.event;
var element = evt.target || evt.srcElement;
while (element){
console.log(element);
element = element.parentNode;
}
};