Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
150 views
in Technique[技术] by (71.8m points)

javascript - Check event.target.parentElement with matchesSelector js

Not concerned about old browser fallback. Also, can't use libraries.

I have an event object. I am testing the event.target against a css selector via matchesSelector:

event['target'].matchesSelector('css selector here');

this works, as does:

event['target']['parentElement'].matchesSelector('css selector here');

...and:

event['target']['parentElement']['parentElement'].matchesSelector('css selector here');

What I'm looking for is some possible object method beyond my understanding that I could use to check each parentElement all the way up for a match, without a for loop. My focus is on efficiency.

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The closest() function will do what you need.

It starts from the element itself, and traverses parents (heading toward the document root) until it finds a node that matches the provided selectorString. Somewhat similar to jQuery's parents() function.

So your code will look like that:

event.target.closest(selectorString)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...