Reputation: 587
I am facing the following situation:
mousemove
event registered on cells of a table which resides in this hierarchy BODY -> Something1 -> Something2 -> Something3 -> Table -> Cell
e.target.offsetParent.offsetParent.offsetParent.id
- which is hardcoded & I don't like ite.target
and match the class [Yes, I know the element's class name] of the specific parent whose ID is what I would like to retrieve. Now, the question is, is there a better way to achieve this? Something like jQuery's find or something?
Example: e.target.findOnOffsetParents('<.CLASS_NAME>');
EDITED: Included code involved
$(document).on("mousemove", 'table', function (e) {
Console.log($(e.target).parents('.object').length); //this one results '0'
Console.log($(e.target).closest('.object').length); // so does this
Console.log($(e.target).parents().find('.object')); //this one picks all elements with class name 'object' regardless of whether or not it is a parent of the e.target
});
Upvotes: 0
Views: 2716
Reputation: 10838
Depending on what you're searching for, and what you're doing with the result(s), you'll want to use either .parents()
or .closest()
$(elem).parents('.object')
- returns all parents of elem
with a class of object
$(elem).closest('.object')
- returns the first parent of elem
that has a class of object
I would assume you want the latter, which would be:
$(e.target).closest('.object')
This jsFiddle shows how each works in a set-up similar to what you've mentioned in your question
Upvotes: 2