2

The following script is supposed to append an element. I first check if the element exists, if not i create it and append it. The problem is that, for some reason, the checking doesn't seem to work, it keeps creating the element over and over...

Question: How to check for the existence of an element after append ?

my jsfiddle:

https://jsfiddle.net/mr54fbrL/

$(document).on("click", ".multilevel p.level", function(e) {

    var box = $(this).next(".itemMenuBox"); // box you want to interact with

    // if box does not exist, add it!
    if( !box.length ) {
        alert('not found, add it!');

        var box = $("<div></div>")
            .attr("class", 'itemMenuBox').text('new box')
            .appendTo($(this));
    } else {
        alert('found box');
    }
});
Marco
  • 2,687
  • 7
  • 45
  • 61
  • 2
    You use `.appendTo` but check for `.next`. Either you want to insert after with `.insertAfter` or you want to find it with `.find` or `.children`. – Karl-André Gagnon Sep 19 '16 at 19:01
  • fudge! i did not realize i was inserting the element as a child and not a sibling!!! Merci Karl-André – Marco Sep 19 '16 at 19:04

1 Answers1

1

Use this Js:

$(document).on("click", ".multilevel p.level", function(e) {
        if($(this).find('div').hasClass('itemMenuBox')){
          alert('found box');
        }else{
              alert('not found, add it!'); 
             var box = $("<div></div>")
                .attr("class", 'itemMenuBox').text('new box')
                .appendTo($(this));
         }      
    });
Sikander
  • 654
  • 1
  • 7
  • 21