jQuery - Check if DOM element already exists

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

提交回复
热议问题