JQuery-检查 DOM 元素是否已经存在

我试图通过 Ajax 和 jQuery 动态地添加一些表单元素。 我希望确保不会重复创建同一个元素,所以我只想在它还没有被添加到 DOM 的情况下添加它。

我的所有元素都有一个惟一的 CSS id,例如:

$('#data_1')

我使用以下方法来检查元素是否已经存在:

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

但是,它只适用于首次加载时已经是页面一部分的元素。

如何检查页面加载后动态创建的元素?

任何建议都不胜感激。

谢谢。

138885 次浏览

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.

Guess you forgot to append the item to DOM.

Check it HERE.

Just to confirm that you are selecting the element in the right way. Try this one

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

if ID is available - You can use getElementById()

var element =  document.getElementById('elementId');
if (typeof(element) != 'undefined' && element != null)
{
// exists.
}

OR Try with Jquery -

if ($(document).find(yourElement).length == 0)
{
// -- Not Exist
}

In this case, you may want to check if element exists in current DOM

if you want to check if element exist in DOM tree (is attached to DOM), you can use:

var data = $('#data_1');
if(jQuery.contains(document.documentElement, data[0])){
// #data_1 element attached to DOM
} else {
// is not attached to DOM
}
if ($('#some_element').length === 0) {
//If exists then do manipulations
}
(()=> {
var elem = document.querySelector('.elem');
(
(elem) ?
console.log(elem+' was found.') :
console.log('not found')
)
})();

If it exists, it spits out the specified element as a DOM object. With JQuery $('.elem') it only tells you that it's an object if found but not which.

No to compare anything, you can simply check that by this...,.

if(document.getElementById("url")){ alert('exit');}
if($("#url")){alert('exist');}

you can also use the html() function as well like

if($("#url).html()){alert('exist');}

This question is about whether an element exists and all answers check if it doesn't exist :) Minor difference but worth mentioning.

Based on jQuery documentation the recommended way to check for existence is

if ($( "#myDiv" ).length) {
// element exists
}

If you prefer to check for missing element you could use either:

if (!$( "#myDiv" ).length) {
// element doesn't exist
}

or

if (0 === $( "#myDiv" ).length) {
// element doesn't exist
}

Note please that in the second option I've used === which is slightly faster than == and put the 0 on the left as a Yoda condition.

Also think about using

$(document).ready(function() {});

Don't know why no one here came up with this yet (kinda sad). When do you execute your code??? Right at the start? Then you might want to use upper mentioned ready() function so your code is being executed after the whole page (with all it's dom elements) has been loaded and not before! Of course this is useless if you run some code that adds dom elements after page load! Then you simply want to wait for those functions and execute your code afterwards...