Bilal Hussain Bilal Hussain - 7 months ago 80
HTML Question

how to check if a ul has a particular li with jQuery?

I am working on the two ul lists. What I need is if someone click on the list item in list1 ,it will check the 2nd list if it contains the clicked element or not.If it does not contain the element then copy it else just return.
What I have done so far is I am moving the elements successfully between the list but if I apply a check on it everything stops working.
Here is the link of jsfiddle

$().ready(function() {
var classHighlight = 'highlight';
var $thumbs = $('ul li').on("click", function(e) {
//e.preventDefault();
debugger;
$thumbs.removeClass(classHighlight);
$(this).addClass(classHighlight);
});
$('#select1').on ("dblclick","li", function(){
//if($("#select2").has($(this))
//return;
//else
$(this).clone().appendTo('#select2').removeClass('highlight');
});
$('#select2').on ("dblclick","li", function(){
$(this).remove();
});
$('#add').click(function() {
$('#select1 .highlight').clone().appendTo('#select2').removeClass(classHighlight);
});
$('#remove').click(function() {
$('#select2 .highlight').remove();
});
});


If you un comment the above lines in code everything stop working.
Can any one please help me with this?
Thanks

Answer

Try this check:

var check = function(li) {
    return $("#select2 li").filter(function(i, li2) {
        return $(li2).text() == $(li).text();
    }).length > 0;
};

Demo

As you're using clone(), you can't compare the new cloned element using is() or has() with the orignal one, because it is a new element, it isn't the same, as stated in clone's docs:

Create a deep copy of the set of matched elements

So it's a copy.