Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - Check if DOM element already exists

Tags:

jquery

I am trying to add some form elements dynamically via Ajax with jQuery. I want to make sure that I don't create the same element twice, so I only want to add it if it hasn't already been added to the DOM.

All of my elements have a unique CSS id, for example:

$('#data_1') 

I am using the following to check if the element already exists:

if ($('some_element').length == 0) {     //Add it to the dom } 

However, it only works for elements which were already part of the page when it first loaded.

How do I also check for elements which were dynamically created after the page was loaded?

Any advice is appreciated.

Thanks.

like image 903
Dan Avatar asked Apr 04 '11 13:04

Dan


People also ask

How do you check class is exists in DOM jQuery?

The hasClass() is an inbuilt method in jQuery which check whether the elements with the specified class name exists or not. Syntax: $(selector). hasClass(className);

How do I check if an element is available?

Answer: Use the jQuery . length Propertylength property to determine whether an element exists or not in case if you want to fire some event only if a particular element exists in DOM.


1 Answers

This should work for all elements regardless of when they are generated.

if($('some_element').length == 0) { } 

write your code in the ajax callback functions and it should work fine.

like image 78
rahul Avatar answered Oct 04 '22 05:10

rahul