2

Example:

var $doesNotYetExistInTheDOM = $('<span/>'); // create new jQuery element
                                             // outside of the DOM
var $doesExistInTheDOM = $('span');  // selected element from the DOM

Is there a way to check if a jQuery selected object exists in the DOM?

thecodeparadox
  • 86,271
  • 21
  • 138
  • 164
jondavidjohn
  • 61,812
  • 21
  • 118
  • 158

2 Answers2

2

Just try this:

$('span').length // if exists it return > 0 or 0

if you want check using any particular id or class then try:

$('span.some').length

or

$('span#some').length

Using you variable:

var $doesNotYetExistInTheDOM = $('<span/>');

$(document,$doesNotYetExistInTheDOM).length

var $doesExistInTheDOM = $('span'); 

$(document,$doesExistInTheDOM ).length

jQuery has a method called .size() (but .length is preferred)

Use:

$('span.some').size()

$('span#some').size()

var $doesNotYetExistInTheDOM = $('<span/>');

$(document,$doesNotYetExistInTheDOM).size()
thecodeparadox
  • 86,271
  • 21
  • 138
  • 164
1

You can check by trying to find it in the document:

!!$(document).find($doesNotYetExistInTheDOM).length // false
!!$(document).find($doesExistInTheDOM).length // true
Trevor
  • 9,518
  • 2
  • 25
  • 26