在自然JavaScript中编写jQuery replaceWith()的最佳方法

时间:2012-04-15 19:24:53

标签: javascript jquery load replacewith

有一个功能尽快点击页面的问题,所以我需要用纯JavaScript编写它并将其包含在头部。不确定如何去做,因为据我所知,通过使用.replace(),新元素将被移动到页面上的不同位置。 jQuery的replaceWith()行为是理想的。

$("#imagefiles").replaceWith("<input type='file' name='imagefiles' id='imagefiles' />");

3 个答案:

答案 0 :(得分:8)

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


编辑我不是我:

var image = document.getElementById('imagefiles'), parent = image.parentNode,
input = document.createElement('input');
input.id = input.name = "imagefiles";
input.type = 'file';

parent.replaceChild(input, image);

edited DEMO

答案 1 :(得分:0)

  const node = new DOMParser().parseFromString(html, 'text/html').body.childNodes[0];
  document.getElementById(id).replaceWith(node);

答案 2 :(得分:0)

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

多年以后。现在有一个 childNode.replaceWith() 但它并不严格等同于 JQuery replaceWith();也不兼容I.E.

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

https://developer.mozilla.org/en-US/docs/Web/API/ChildNode/replaceWith

相关问题