0

I'm trying to detach a DOM element to append it to another DOM element. But jQuery refuses to do anything, silently.

Thing is, I can't use a string selector, because I don't know how to select this element. I've stored it in a variable when I first appended some html code to the initial parent (through "appendTo".

this.element = $(my_html_string).appendTo(some_dom_parent);

And that works fine. The code that is not working as expected, is following:

this.transferTo = function(dom_parent)
{
    $(this.element).detach()
    $(this.element).appendTo(dom_parent);
}

What happens is:

  • The element is NOT removed from wherever it is.
  • The element IS appended to the new parent.
  • Previously bind click events are triggered on both elements.
  • That click event appends a popup dialog to the element. It's being appended to the element in the new parent, always, regardless which one I click.

I tried some hardcoded detach like:

$('#very_specific_id').detach()

... and it works. But thing is, I don't have IDs placed around, and sounds like a very bad way to do this.

So the problem seems to rely on the fact I'm saving a jQuery DOM Element and trying to use .detach from it, instead of using a $(".query") like everyone else.

Ideas? Workarounds? Thanks!

ArtPulse
  • 365
  • 4
  • 16
  • Can you create a demo? An element can't be in two places at once. There must be a `.clone()` taking place somewhere. –  Jul 17 '12 at 02:51

1 Answers1

0

Try changing this:

this.transferTo = function(dom_parent)
{
    $(this.element).detach()
    $(this.element).appendTo(dom_parent);
}

to this:

this.transferTo = function(dom_parent)
{
    var $thisElement = $(this.element);
    $thisElement.detach()
    $thisElement.appendTo(dom_parent);
}
qwertymk
  • 34,200
  • 28
  • 121
  • 184
  • Nope, but your answer made me realize I'm a moron. Something was wrong with the framework I'm using, but all these codes are fine -.- Thank you... – ArtPulse Jul 17 '12 at 03:00
  • You should be able to skip the `.detach()` step. If you `.append()` or `.appendTo()` a single parent that does a _move_ (if you append to multiple parents that does a _copy_). – nnnnnn Jul 17 '12 at 03:45