Bilal Hussain
Bilal Hussain

Reputation: 191

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 if the 2nd list 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

Upvotes: 1

Views: 3448

Answers (2)

Quentin Engles
Quentin Engles

Reputation: 2832

You have a missing paren.

This if($("#select2").has($(this)) should be this if($("#select2").has($(this))).

Also you can just pass this: if($("#select2").has(this))

And you have to check length: if($("#select2").has(this).length)

Upvotes: 1

DontVoteMeDown
DontVoteMeDown

Reputation: 21465

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.

Upvotes: 4

Related Questions