Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a dynamically created element already exists using jQuery?

I create an element dynamically:

var $el = $('<div class="someclass"></div>');

I want to append the element ($el) somewhere, but it shouldn't have an id.

How do I know if it has been appended before or not?

edit
I thought this should work

if($($el, "#target").length == 0)
    $("#target").append($el);

but that was wrong

like image 893
Omid Avatar asked Dec 27 '22 08:12

Omid


2 Answers

If I understand, and you need to check if another <div class='someclass'> already exists before appending $el, you can do:

if ($("div.someclass").length === 0) {
  // it has not been created yet, create a new one
  var $el = $('<div class="someclass"></div>');
}

To check if it is already a child node of some other element, use .find()

if ($("#parentNode").find("div.someclass").length === 0 {
  // it has not been created yet, create a new one
  var $el = $('<div class="someclass"></div>');
}
like image 24
Michael Berkowski Avatar answered Dec 31 '22 15:12

Michael Berkowski


You can simply check to see if it has a parent:

var $el = $('<div class="someclass"></div>');
//Code you wrote that may or may not attach it to the DOM

if($el.parent().length === 0) {
    //The element has not been added to the DOM because it doesn't not have a parentNode
}

However, if you have no idea what is actually being done with the element, you may have other problems with your code.

like image 158
Dennis Avatar answered Dec 31 '22 13:12

Dennis