Move an element to another parent after changing its ID
Asked Answered
B

1

21

I have HTML like this:

<span class="file-wrapper" id="fileSpan">
    <input type="file" name="photo[]" id="photo" />
    <span class="button">Click to choose photo</span>
</span>

I want to extract the input field from there, change its ID and put it in an other div.

How can I do that? If jQuery is needed that's okay, but if it can be without that would be great.

Brasilein answered 26/9, 2011 at 12:59 Comment(0)
U
53

It's certainly easy in jQuery:

// jQuery 1.6+
$("#photo").prop("id", "newId").appendTo("#someOtherDiv");

// jQuery (all versions)
$("#photo").attr("id", "newId").appendTo("#someOtherDiv");

Working demo: http://jsfiddle.net/AndyE/a93Az/


If you want to do it in plain ol' JS, it's still fairly simple:
var photo = document.getElementById("photo");
photo.id  = "newId";
document.getElementById("someOtherDiv").appendChild(photo); 

Working demo: http://jsfiddle.net/AndyE/a93Az/1/

Utilitarianism answered 26/9, 2011 at 13:1 Comment(7)
@Royi: easily ported to older versions, just change prop() to attr().Utilitarianism
Shouldn't we opt for the newest version of jQuery when possible anyways?Kinny
@Bracketworks: I would say so. IIRC, prop() should be a little more efficient than attr() because there's less work to do compatibility-wise.Utilitarianism
It's worth explaining that when you use appendChild (or append or appendTo) with an existing DOM element, that element is moved to the new location, not copied there.Taphouse
@mblase75: maybe, but isn't that fairly explanatory when reading or testing the code? In any case, the working demos should clear up any confusion :-)Utilitarianism
@AndyE: it's not necessarily obvious from the dictionary definition of "append." That's why it's worth explaining to someone new to the technique.Taphouse
@mblase75: my point was that the use of "append" in the answer and no mention of the word "move" implies that appendTo works in that way.Utilitarianism

© 2022 - 2024 — McMap. All rights reserved.