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?
Try
Here are some more ways to do the same:
Or using the
containsmethod that was built for this task. It only accepts DOM nodes, so we need to unwrap it from the jQuery objectA pure DOM way will be to use the
Node.compareDocumentPositionmethod. In the above example,