source

jQuery - Check if DOM element already exists

ittop 2023. 9. 19. 21:22
반응형

jQuery - Check if DOM element already exists

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.

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.

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.

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
}

Guess you forgot to append the item to DOM.

Check it HERE.

한다면ID사용 가능 - 를 사용할 수 있습니다.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
}
(()=> {
    var elem = document.querySelector('.elem');  
    (
        (elem) ? 
        console.log(elem+' was found.') :
        console.log('not found')
    )
})();

존재하는 경우 지정된 요소를 DOM 개체로 표시합니다.JQuery와 함께$('.elem')발견된 물체라고만 알려줄 뿐 어떤 물체인지는 알려주지 않습니다.

if ($('#some_element').length === 0) {
    //If exists then do manipulations
}

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

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...

언급URL : https://stackoverflow.com/questions/5538961/jquery-check-if-dom-element-already-exists

반응형