Determine whether a jQuery selection is in the DOM
I have a jQuery selection that either originated as a newly created element (e.g. $("<div/>")
) and has no parent, or is actually an element开发者_高级运维 in the DOM.
What's the most efficient way to determine whether or not the selected element is actually in the current DOM tree?
One possibility is to call .parent()
, but I suspect there's a more efficient way.
The idea to ask for a .parent()
is not that bad, actually its a pretty common way. Anyway, you could also use the .contains()
method.
var newdiv = $('<div>');
if( $.contains(document.body, newdiv[0]) ) {
}
reference: .contains()
example: http://www.jsfiddle.net/gGPav/
performance: http://jsperf.com/contains-vs-parentnode
looking at the performance, I would also go with node.parentNode
I realized that both my question and Andy's solution (using node.parentNode
) can be generalized. Here's a full version that will work for any jQuery selection, even if it has at least one ancestor.
/**
* Returns true if this selection is part of the current DOM;
* false if it's a fragment.
* @return {Boolean}
*/
jQuery.fn.inDom = function() {
// Get the first element in the jQuery selection
var node = this[0];
while (node) {
if (node.nodeType === Node.DOCUMENT_NODE) {
return true;
}
node = node.parentNode;
}
return false;
}
Look into the jQuery index method.
Something like $(yourDiv).index('body div')
can tell you a lot.
Give the newly created element an ID and query for the ID.
精彩评论