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
  • 84,459
  • 21
  • 136
  • 161
jondavidjohn
  • 60,871
  • 21
  • 115
  • 157

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
  • 84,459
  • 21
  • 136
  • 161
1

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

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