在自然 JavaScript 中编写 jQuery 的 replaceWith() 的最佳方式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10165262/
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
best way to write jQuery's replaceWith() in natural JavaScript
提问by technopeasant
Having trouble with a function hitting the page as soon as possible, so i need to write it in pure javascript and include it in the head. not sure how to go about it, because as i understand it, by using .replace() the new element will be moved to a different location on the page. jQuery's replaceWith() behavior is ideal.
有一个函数尽快访问页面时遇到问题,所以我需要用纯 JavaScript 编写它并将其包含在头部。不知道如何去做,因为据我所知,通过使用 .replace() 新元素将被移动到页面上的不同位置。jQuery 的 replaceWith() 行为是理想的。
$("#imagefiles").replaceWith("<input type='file' name='imagefiles' id='imagefiles' />");
回答by qwertymk
var image = document.getElementById('imagefiles'), parent = image.parentNode,
tempDiv = document.createElement('div');
tempDiv.innerHTML = "<input type='file' name='imagefiles' id='imagefiles' />"
var input = tempDiv.childNodes[0];
parent.replaceChild(input, image);
DEMO
演示
EDIT as per am not i am:
按我不是我编辑:
var image = document.getElementById('imagefiles'), parent = image.parentNode,
input = document.createElement('input');
input.id = input.name = "imagefiles";
input.type = 'file';
parent.replaceChild(input, image);