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
478 views
in Technique[技术] by (71.8m points)

jquery - Best way to find out if element is a descendant of another

I am in the process of implementing jQuery, and taking out Prototype libraries in my codebase, and I am wondering if you could give me the best way to implement this functionality in jQuery. I am familiar with the jQuery ancestor>descendant syntax, but just want to check if an element is a descendant by true of false, like the code below: can someone give me the most efficient jQuery solution for this ?

<div id="australopithecus">
  <div id="homo-herectus">
    <div id="homo-sapiens"></div>
  </div>
</div>

$('homo-sapiens').descendantOf('australopithecus');
// -> true

$('homo-herectus').descendantOf('homo-sapiens');
// -> false
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

In jQuery 1.6, you can use the following code generically, e.g. targetElt and parentElt can both be DOM elements or jQuery-wrapped objects, as well as selectors:

$(targetElt).closest(parentElt).length > 0

Some of the other answers require you to refer to elements by their IDs, which isn't useful if all you have is a DOM element without an ID. Also, if you want to make sure that the targetElt is a strict descendant of parentElt (in other words, you don't want to count parentElt as its own descendant), make sure to add a targetElt != parentElt check before your call to .closest(), or use .parents().find() as Jonathan Sampson suggests.


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

1.4m articles

1.4m replys

5 comments

56.8k users

...