如何使用jQuery检查动态创建的元素是否已存在?

Omi*_*mid 2 javascript jquery dom

我动态创建一个元素:

var $el = $('<div class="someclass"></div>');
Run Code Online (Sandbox Code Playgroud)

我想在$el某处附加元素(),但它不应该有id.

我怎么知道它之前是否已被追加?

编辑
我认为这应该工作

if($($el, "#target").length == 0)
    $("#target").append($el);
Run Code Online (Sandbox Code Playgroud)

但那是错的

Den*_*nis 5

您只需检查它是否有父母:

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
}
Run Code Online (Sandbox Code Playgroud)

但是,如果您不知道该元素实际上是做什么的,那么您的代码可能还有其他问题.