"Add if does not exist" in jQuery

I am trying to write a helper function for jQuery that creates an element if it does not already exist. So far, I:

function setup(element, parent){
  if($(parent).child(element).length == 0){
    $(parent).append('<div class="'+element+'"></div>');
  }
}

but I wonder if this is a problem. It?

(The reason I want to is because I can use JSON content and put it in the right place. If the right place exists, I just update the content. If it does not exist, I will create it.)

+3
source share
2 answers

If you expect what elementwill be the name of the class, you will also need to use the class selector for testing:

function setup(className, parent) {
    if ($(parent).children("."+className).length == 0) {
        $(parent).append("<div></div>").children(":last-child").addClass(className);
    }
}
+2
source

Assuming you identify your divs with id and have an array of elements with identifiers as keys

function mergeIn(elements,parent){
 $(parent).children('div').each(function(){
  $(this).html(elements[$(this).attr('id')]); 
  delete elements[$(this).attr('id')]; 
 });
 //only not present elements remain in the array
 for(var i in elements){
  $(parent).append('<div id="'+i+'">'+elements[i]+'</div>');
 }
}

and all this is done :)

+2
source

Source: https://habr.com/ru/post/1733957/


All Articles