vandelay vandelay - 1 month ago 8
Javascript Question

JQuery, clone and append only if target div not already has div with id

I'm trying to clone and append a div to another div. But I only want to move it if the target div does not already contain a clone.

function addToPortFolio(cl) {
var className = cl.attr('id');
console.log(className);

if ($(".portfolioWrapper").has("#" + className).length > 0){
console.log('exists');
} else {
cl.clone().appendTo('.portfolioWrapper');
console.log('not exist');
}
}


Below is the console log:

not exist
AAA.L
not exist
AAA.L
not exist
AAAP
not exist
AAAP
exists
AAAP
exists
AAAP
exists


It's behaving very odd, and can't really figure out why. If I continously click the div with class AAA.L it will not work, but AAAP will?

Is this a general bad practise?

Answer

This should work:

function addToPortFolio(cl) {
  if ($(".portfolioWrapper").find($('".' + cl.classList.join('.') + '"')).length >  0){ 
    console.log('exists');    
  } else {
    cl.clone().appendTo('.portfolioWrapper');
    console.log('just added it');
  }
}
Comments