Srii
Srii

Reputation: 587

Javascript - event.target.offsetParent

I am facing the following situation:

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

Answers (1)

MDEV
MDEV

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

Related Questions