views:

28

answers:

2

Is it possible, in either the jQuery API or the DOM, to check if an element exists on the page or not?

Consider these two variables:

var selected = $('span#mySpan');
var created = $('<span id="mySpan">Testing</span>');

Both will return a jQuery object containing a span element. Is there any way to tell that the first exists on the page, and the second one does not?

+2  A: 

Try

$(created).parents("html").length

Here are some more ways to do the same:

$(document).find(created).length
$(created).parents(document).length

Or using the contains method that was built for this task. It only accepts DOM nodes, so we need to unwrap it from the jQuery object

$.contains(document, created.get(0))

A pure DOM way will be to use the Node.compareDocumentPosition method. In the above example,

// get the DOM node
var createdNode = created.get(0);
var position = document.compareDocumentPosition(createdNode);
var isNotInDocument = (position & Node.DOCUMENT_POSITION_DISCONNECTED) != 0;
Anurag
Beautiful in its simplicity :)
Adam Lassek
It is simple, but not fool-proof :) Consider a node `p` inside `$("<html><body><p>hello</p></body></html>")` will return 1.
Anurag
@Anurag I can live with that; if they're generating a second Html and Body then things are supposed to break ;-)
Adam Lassek
@Anurag `$.contains` looks like the winner. It should be noted that while `compareDocumentPosition` is the 'correct' way, it is not supported cross-platform.
Adam Lassek
A: 

The only way I can think of doing this, aside from some kind of an extension to the underlying DOM api is to grab a copy of the entire DOM tree and then do a comparison against it.

In your example, won't your second span have no parent? In valid HTML a span should always have a parent. Just rules like that, assuming valid HTML/XHTML, might be useful.

jMerliN