Steve
Steve

Reputation: 4918

How to find an element with a given ID in a set of DOM elements?

I have some divs in a jquery set, called set$, that have all been moved together, and I want to be able now to UNDO the move. Before I did the move I cloned set$ with:

set_before_move$ = set$.clone()

After the move, the set$ members are all moved and the set_before_move$ members should have the original offset. My thought to undo the move was to go through set$ and for each member

  1. get the id
  2. find the element with that id in set_before_move$
  3. pull the offset from the set_before_move$ member
  4. apply that offset in the set$ member

The code I have looks like:

var off;
set$.each(function () {
   moved_id = $(this).attr('id');  // get the id of this element
   unmoved_el$ = set_before_move$.([id=moved_id]); // find element in set_before_move$
   off = unmoved_el$.offset();    // get its offset
   $(this).offset(off);   // put the offset into the set$ member
});

But it doesn't like the square brackets. Does someone see the right way to do this?

Thanks

Upvotes: 1

Views: 61

Answers (2)

Boaz
Boaz

Reputation: 20230

You can use the filter() method, to reduce the jQuery object set_before_move$ to a set of a single element with moved_id.

For example:

var moved_id = 'some-id'; 
unmoved_el$  = set_before_move$.filter(function() {
    return $(this).attr('id') == moved_id;
});

Upvotes: 1

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85653

You need to set true:

set_before_move$ = set$.clone(true)

Upvotes: 1

Related Questions