jQuery - Check if DOM element already exists

前端 未结 10 1585
萌比男神i
萌比男神i 2020-12-04 21:01

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\

相关标签:
10条回答
  • 2020-12-04 21:10

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

    0 讨论(0)
  • 2020-12-04 21:14
    (()=> {
        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.

    0 讨论(0)
  • 2020-12-04 21:14

    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');}
    
    0 讨论(0)
  • 2020-12-04 21:15

    Guess you forgot to append the item to DOM.

    Check it HERE.

    0 讨论(0)
  • 2020-12-04 21:17

    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.

    0 讨论(0)
  • 2020-12-04 21:22

    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
    }
    
    0 讨论(0)
提交回复
热议问题