编写jQuery的最佳方法&x27;在自然JavaScript中替换为()

编写jQuery的最佳方法&x27;在自然JavaScript中替换为(),javascript,jquery,load,replacewith,Javascript,Jquery,Load,Replacewith,在函数尽快进入页面时遇到问题,因此我需要用纯javascript编写它,并将其包含在头部。不知道该怎么做,因为据我所知,通过使用.replace()新元素将被移动到页面上的其他位置。jQuery的replaceWith()行为非常理想 $("#imagefiles").replaceWith("<input type='file' name='imagefiles' id='imagefiles' />"); $(“#图像文件”)。替换为(“”); const node=new

在函数尽快进入页面时遇到问题,因此我需要用纯javascript编写它,并将其包含在头部。不知道该怎么做,因为据我所知,通过使用.replace()新元素将被移动到页面上的其他位置。jQuery的replaceWith()行为非常理想

$("#imagefiles").replaceWith("<input type='file' name='imagefiles' id='imagefiles' />");
$(“#图像文件”)。替换为(“”);
const node=new DOMParser().parseFromString(html,'text/html').body.childNodes[0];
document.getElementById(id).replaceWith(节点);
let element=document.getElementById(“imagefiles”);
元素。insertAdjacentHTML(“afterend”,“afterend”);
element.parentNode.removeChild(元素);
几年后。现在有了一个childNode.replaceWith(),但它并不是严格等同于JQuery replaceWith();它也不兼容,即

上面的代码从给定的HTML创建一个文档片段,并将其插入DOM中的原始元素之后,然后删除原始元素,有效地替换它


再次使用jQuery有什么问题?
.replace()
用于字符串。请不要将其用于DOM。你能更详细地描述一下你的问题吗?您的意思是希望元素一出现就被替换,而不是等待DOM的其余部分准备就绪吗?为什么要使用
div
?直接创建
输入将更快、更少的代码<代码>输入=document.createElement('input');input.type=“文件”;input.id=input.name=“imagefiles”@qwertymk它在JSFIDLE中工作,但我的webinspector在最后一行显示了一个错误:“未捕获的SyntaxError:意外标记非法”@technofarmer:哥们,你得多投票让人们回答你,当你问128个问题时,总是有11票?@technofarmer:如果你从JSFIDLE复制/粘贴一些不可见和非法的字符。最好从这里复制代码。
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);
var image = document.getElementById('imagefiles'), parent = image.parentNode,
input = document.createElement('input');
input.id = input.name = "imagefiles";
input.type = 'file';

parent.replaceChild(input, image);
let element = document.getElementById("imagefiles");
element.insertAdjacentHTML("afterend","<input type='file' name='imagefiles' id='imagefiles' />");
element.parentNode.removeChild(element);