Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if an object with an ID already exists on the page? [duplicate]

Possible Duplicate:
Is there an “exists” function for jQuery

Say for instance you have the div:

<div id="hello"></div> 

And you are dynamically creating a div:

<div id="hello"></div> 

Is there a function you can use in Jquery which will check to see if the object with the ID you are trying to create already exists on the page?

like image 202
TaylorMac Avatar asked May 19 '11 01:05

TaylorMac


People also ask

What method's would you use to check if an element has a specific ID and if so replace it with a different ID?

Approach 2: First, we will use document. getElementById() to get the ID and store the ID into a variable. Then use JSON. stringify() method on the element (variable that store ID) and compare the element with 'null' string and then identify whether the element exists or not.

How do you find if element with specific ID exists or not in jQuery?

In jQuery, you can use the . length property to check if an element exists. if the element exists, the length property will return the total number of the matched elements. To check if an element which has an id of “div1” exists.

How do you check if an object contains a string in Javascript?

The includes() method returns true if a string contains a specified string. Otherwise it returns false .


2 Answers

For jQuery method you could go with

if($("#selector").length) {     //object already exists } 
like image 106
Marek Karbarz Avatar answered Oct 02 '22 02:10

Marek Karbarz


if (document.getElementById('hello')) {     // yup, already there } 

Or, the jQuery way:

if ($('#hello').length) {     // yup, already there } 
like image 30
deceze Avatar answered Oct 02 '22 04:10

deceze