Marc
Marc

Reputation: 303

Compare Elements via jQuery

I'm in a situation where I want to check if two elements (one is clicked and another one a reference) are the same, what I'm trying to do is:

$("#process li").click(function() {
   currentElement = $(this);
   referenceElement = $("#process li:first-child");
   if (currentElement === referenceElement) {
        $(".mark").removeClass("mark");
        $(this).addClass("mark");
   }
});

So what I want is to check if the clicked <li> is the first child of the ul#process and if so first remove a .mark class from another element and then add it to the clicked one. I don't get any working result - ideas anyone?


UPDATE:

Thanks you very much! This is my solution:

$("#processlist li").click(function() {
  currentElement = $(this);
  if (currentElement.is('li:first-child')) {
    $(this).addClass("mark");
  }
});

Now if I click on a

  • , if it is the first child of this list, the class .mark is added - sweet!

    Upvotes: 1

    Views: 22

  • Answers (2)

    error
    error

    Reputation: 756

    You need to extract the DOM element from the jQuery object. You can use the get method of jQuery for this.

    e.g. if( currentElement.get( 0 ) === referenceElement.get( 0 ) )

    Upvotes: 0

    Rory McCrossan
    Rory McCrossan

    Reputation: 337560

    Comparing objects in JS is very troublesome. The simplest way is to just pick a few key properties and compare those, eg:

    if (currentElement.prop('id') === referenceElement.prop('id') {
        // rest of your code...
    }
    

    However, given your use case you could use is:

    if (currentElement.is('#process li:first-child')) {
        // rest of your code...
    }
    

    Example fiddle

    Upvotes: 2

    Related Questions