Question

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!

Was it helpful?

Solution

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);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top