admin管理员组文章数量:1327939
Given two jquery objects, Is there some way I tell which one is "further ahead" in the document tree than the other? In other words, with a document
<p id="p1" ></p>
<div id="div1">
<p id="p2"></p>
</div>
<p id="p3"></p>
Is there some function that behaves thus?
$("#p1").isBefore($("#p2")); // == true
$("#p3").isBefore($("#p2")); // == false
$("#p1").isBefore(#("#p3")); // == true
Note that I care about position in the HTML tree of the document, not physical position on the screen.
Given two jquery objects, Is there some way I tell which one is "further ahead" in the document tree than the other? In other words, with a document
<p id="p1" ></p>
<div id="div1">
<p id="p2"></p>
</div>
<p id="p3"></p>
Is there some function that behaves thus?
$("#p1").isBefore($("#p2")); // == true
$("#p3").isBefore($("#p2")); // == false
$("#p1").isBefore(#("#p3")); // == true
Note that I care about position in the HTML tree of the document, not physical position on the screen.
Share Improve this question asked Oct 5, 2010 at 1:45 wxswxs 5,8575 gold badges39 silver badges52 bronze badges2 Answers
Reset to default 12You can make a function that does this, like this:
(function($) {
$.fn.isBefore = function(elem) {
if(typeof(elem) == "string") elem = $(elem);
return this.add(elem).index(elem) > 0;
}
})(jQuery)
You can try it out here, the first line is so it can also take a selector string directly, for example:
$("#p1").isBefore("#p2");
What this does is .add()
the additional element (or selector) (which jQuery keeps in document order) and then checks if it's the second of the two.
If the selector this is run against has more than one element, this returns true if any of those elements are "before" the passed in element or selector, so given your markup for example $("p").isBefore("#p2")
would be true
, since at least one <p>
occurs "before" #p2
.
You can try it that way:
alert($('#p1,#p2')[0]===$('#p1')[0]);
alert($('#p3,#p2')[0]===$('#p3')[0]);
alert($('#p1,#p3')[0]===$('#p1')[0]);
...fetch both objects and look which is the first.
function for better usability:
(function($) {
$.fn.isBefore = function(elem) {
return ($([elem.selector,this.selector].join(','))[0]===this[0]);
}
})(jQuery);
本文标签: javascriptRelative position in DOM of elements in jQueryStack Overflow
版权声明:本文标题:javascript - Relative position in DOM of elements in jQuery - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742163853a2425453.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论