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
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>');
}
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.
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