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.parentN开发者_开发知识库ode, but I'm stuck on the traversing part. Any gurus out there that can help me out, it would be greatly appreciated.
var 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;
}
};
精彩评论