Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
47
rated 0 times [  49] [ 2]  / answers: 1 / hits: 109720  / 11 Years ago, fri, september 6, 2013, 12:00:00

I am trying to find the closest element with a specific tag name without jquery. When I click on a <th> I want to get access to the <tbody> for that table. Suggestions? I read about offset but didn't really understand it too much. Should I just use:



Assume th is already set to clicked th element



th.offsetParent.getElementsByTagName('tbody')[0]

More From » javascript

 Answers
1

Little (very) late to the party, but nonetheless. This should do the trick:



function closest(el, selector) {
var matchesFn;

// find vendor prefix
['matches','webkitMatchesSelector','mozMatchesSelector','msMatchesSelector','oMatchesSelector'].some(function(fn) {
if (typeof document.body[fn] == 'function') {
matchesFn = fn;
return true;
}
return false;
})

var parent;

// traverse parents
while (el) {
parent = el.parentElement;
if (parent && parent[matchesFn](selector)) {
return parent;
}
el = parent;
}

return null;
}

[#75847] Thursday, September 5, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
lara

Total Points: 462
Total Questions: 100
Total Answers: 102

Location: Jersey
Member since Mon, Jun 14, 2021
3 Years ago
lara questions
;