jQuery - Check if DOM element already exists

前端 未结 10 1593
萌比男神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: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
    }
    

提交回复
热议问题