Steve Steve - 9 months ago 30
Javascript Question

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
members are all moved and the
members should have the original offset. My thought to undo the move was to go through
and for each member

  1. get the id

  2. find the element with that id in

  3. pull the offset from the

  4. apply that offset in the

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?



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;