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.

Andy E
  • 338,112
  • 86
  • 474
  • 445
homerun
  • 19,837
  • 15
  • 45
  • 70

1 Answers1

50

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/

Andy E
  • 338,112
  • 86
  • 474
  • 445
  • @Royi: easily ported to older versions, just change `prop()` to `attr()`. – Andy E Sep 26 '11 at 13:03
  • Shouldn't we opt for the newest version of jQuery when possible anyways? – Dan Lugg Sep 26 '11 at 13:04
  • @Bracketworks: I would say so. IIRC, `prop()` should be a little more efficient than `attr()` because there's less work to do compatibility-wise. – Andy E Sep 26 '11 at 13:09
  • 26
    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. – Blazemonger Sep 26 '11 at 13:14
  • @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 :-) – Andy E Sep 26 '11 at 13:25
  • @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. – Blazemonger Sep 26 '11 at 13:30
  • @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. – Andy E Sep 26 '11 at 13:34