在自然 JavaScript 中编写 jQuery 的 replaceWith() 的最佳方式
best way to write jQuery's replaceWith() in natural JavaScript
在函数
尽快到达页面时遇到问题,所以我需要用纯 JavaScript 编写它并将其包含在头部中。 不知道该怎么做,因为据我了解,通过使用 .replace(),新元素将被移动到页面上的不同位置。 jQuery的replaceWith()行为是理想的。
$("#imagefiles").replaceWith("<input type='file' name='imagefiles' id='imagefiles' />");
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);
编辑演示
const node = new DOMParser().parseFromString(html, 'text/html').body.childNodes[0];
document.getElementById(id).replaceWith(node);
let element = document.getElementById("imagefiles");
element.insertAdjacentHTML("afterend","<input type='file' name='imagefiles' id='imagefiles' />");
element.parentNode.removeChild(element);
多年后。现在有一个 childNode.replaceWith(),但它并不严格等同于 JQuery replaceWith();它也不与 IE 兼容。
上面的代码从给定的 HTML 创建一个文档片段,并将其插入到 DOM 中的原始元素之后,然后删除原始元素,有效地替换它。
https://developer.mozilla.org/en-US/docs/Web/API/ChildNode/replaceWith
相关文章:
- 在localhost Dev Box上测试JSONP请求的最佳方式
- 有条件更新d3.js力图中节点的最佳方法
- 为react组件传递道具的最佳方式
- 与运行长作业(javascript,node.js)的第三方API同步的最佳实践
- 让Webpack管理Quirky AMD定义的最佳方式
- 在承诺链中处理早期回报的最佳方式
- 将jQuery.ech()方法转换为本地JavaScript抽象的最佳方法是什么
- Angularjs 1.5.x本地化最佳实践
- 处理浮点错误的最佳方法是什么
- javascript导入的最佳实践是什么
- MobileFirst:在客户端运行计时器作业-最佳选项
- 在ng重复循环中显示条件内容的最佳方式是什么
- 在phonegap中为android调用onload函数的最佳方式
- 实现比较方法的最佳实践是什么;s的比较类型是在运行时选择的
- 从数组中删除元素的最佳方法是:javascript/jquery
- 链接两个网页或网络应用程序的最佳方式
- 什么's是连接供应商js文件的最佳方式
- Express服务器中语言子域的最佳实践
- 什么's是在javascript中迭代项的最佳方式
- 在自然 JavaScript 中编写 jQuery 的 replaceWith() 的最佳方式