Jquery insertAfter only once if element exist

15,369

Solution 1

Just do a length check. Assuming you have a selector #sel, and you want to insert something after it.

var foo = 'something';
if ($('#sel').length) {
   //do something if elem is present
} else {
    $('#sel').insertAfter(foo);
}

Solution 2

You can check if an element exists by checking the length property of any jQuery object.

Solution 3

Place the following, after amending it to your needs, inside the event handler of your choice:

if (!$('elementID').length) {
    $('<div id="elementID" />').insertAfter('elementSelector');
}

For example:

$('elementSelector').once().click(
    function(){
        if (!$('elementID').length) {
            $('<div id="elementID" />').insertAfter('elementSelector');
        }
    });

References:

Share:
15,369

Related videos on Youtube

shalamhez
Author by

shalamhez

Updated on June 04, 2022

Comments

  • shalamhez
    shalamhez almost 2 years

    How to check if an element exist , and if it does i want the insertAfter to be not valid.And if the element isn't exist, then i want the insertAfter to be valib but only once.My goal is to send only once insertAfter if an element isn't existing and if it does not send anything

    • Sikshya Maharjan
      Sikshya Maharjan almost 13 years
      Insert what element after which element in response to what event? What have you tried, and what went wrong?
  • Wessam El Mahdy
    Wessam El Mahdy about 8 years
    I think you should use one() instead of once().