Compare jQuery Objects

You can't really compare if two jQuery objects are the same...

if ($(selectionOne) === $(selectionTwo)) {

}

You can compare DOM objects though...

if ($(selectionOne)[0] === $(selectionTwo)[0]) {

} 

But that's only really useful if you're comparing a single element, not a collection.

If you need to compare a collection of elements, this StackOverflow thread has the answer:

var divs = $("div");
var divs2 = $("div");

if (divs.length == divs2.length && divs.length == divs.filter(divs2).length) {         
  // They are equal
}

Comments

  1. User Avatar
    Will
    Permalink to comment#

    I think the is method would work in some of those cases too.

  2. User Avatar
    Jimbo
    Permalink to comment#
    var divs = $("div");
    var divs2 = $("div");
    
    if (divs.add(divs2).length === divs.length) {
        // They are equal
    }
    
  3. User Avatar
    Jimbo
    Permalink to comment#
    var divs = $("div");
    var divs2 = $("div");
    
    if (divs.is(divs2)) {
        // They are equal
    }
    
    • User Avatar
      JDongle
      Permalink to comment#

      not true. Is returns true if at least a single item matches.

      var divs = $("#comment-1596556");
      var divs2 = $("#comment-1596557");
      divs = divs.add(divs2);
      divs.is(divs2) //returns true;
      

      is == Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments.
      http://api.jquery.com/is/

  4. User Avatar
    Jimbo
    Permalink to comment#
    var divs = $("div");
    var divs2 = $("div");
    
    if (JSON.stringify(divs) === JSON.stringify(divs2)) {
        // They are equal
    }
    

    (Just kidding.)

Submit a Comment

Posting Code

You may write comments in Markdown. This makes code easy to post, as you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences (```) with double new lines before and after.

Code of Conduct

Absolutely anyone is welcome to submit a comment here. But not all comments will be posted. Think of it like writing a letter to the editor. All submitted comments will be read, but not all published. Published comments will be on-topic, helpful, and further the discussion or debate.

Want to tell us something privately?

Feel free to use our contact form. That's a great place to let us know about typos or anything off-topic.

icon-anchoricon-closeicon-emailicon-linkicon-logo-staricon-menuicon-nav-guideicon-searchicon-staricon-tag