Javascript 更改元素 ID 后将元素移动到另一个父元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7555442/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Move an element to another parent after changing its ID
提问by homerun
I have HTML like this:
我有这样的 HTML:
<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.
我想从那里提取输入字段,更改其 ID 并将其放在另一个 div 中。
How can I do that? If jQuery is needed that's okay, but if it can be without that would be great.
我怎样才能做到这一点?如果需要 jQuery,那没问题,但如果可以没有,那就太好了。
回答by Andy E
It's certainly easy in jQuery:
在 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/
如果你想用普通的 ol' JS 来做,它仍然相当简单:
var photo = document.getElementById("photo");
photo.id = "newId";
document.getElementById("someOtherDiv").appendChild(photo);
Working demo: http://jsfiddle.net/AndyE/a93Az/1/