0

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?

vandelay
  • 1,965
  • 8
  • 35
  • 52
  • Please provide a [mcve]. We have no idea what the html structure is like or how you use this function and therefore can not reproduce your problem – charlietfl Oct 23 '16 at 21:41
  • 1
    Note that using a dot in an ID would require escaping when creating an ID selector per jQuery selector escaping rules http://stackoverflow.com/questions/9930577/jquery-dot-in-id-selector/9930611#9930611 – charlietfl Oct 23 '16 at 21:45
  • Wrong approach. You can check an element's id by just typing $('#id'). – Mightee Oct 23 '16 at 22:05

1 Answers1

1

This should work:

function addToPortFolio(cl) {
  if ($(".portfolioWrapper").find($('.' + cl.className.replace(' ','.'))).length >  0){ 
    console.log('exists');    
  } else {
    cl.clone().appendTo('.portfolioWrapper');
    console.log('just added it');
  }
}
tao
  • 82,996
  • 16
  • 114
  • 150
  • Thanks for the help :) – vandelay Oct 23 '16 at 22:10
  • I've done some tests and updated the method of joining the classnames with a better one. I think initial solution only worked on elements with a single class. You're welcome. – tao Oct 23 '16 at 22:19