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?
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.
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.
The includes() method returns true if a string contains a specified string. Otherwise it returns false .
For jQuery method you could go with
if($("#selector").length) { //object already exists }
if (document.getElementById('hello')) { // yup, already there }
Or, the jQuery way:
if ($('#hello').length) { // yup, already there }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With