tags:

views:

163

answers:

2

I'm trying to write a helper function for jQuery that creates an element if it doesn't already exist. So far I have:

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

but I'm wondering if this isn't a solved problem. Is it?

(The reason I want this is so I can pull in JSON content and put it in the right place. If the right place exists, I'll just update the content. If it doesn't exist, I'll create it.)

+1  A: 

If you expect element to be the class name then you 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);
    }
}
Gumbo
+1 Gave a more thorough solution than mine.
patrick dw
+1  A: 

assuming You identify Your divs with id and have an array of elements with ids 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 it's all done :)

naugtur