jQuery - Check if DOM element already exists

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

    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
    }
    
    0 讨论(0)
  • 2020-12-04 21:31
    if ($('#some_element').length === 0) {
        //If exists then do manipulations
    }
    
    0 讨论(0)
  • 2020-12-04 21:33

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

    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.

    0 讨论(0)
提交回复
热议问题