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

10

我遇到一个问题:需要尽快调用一个函数,所以我需要使用纯JavaScript编写并将其包含在头部。但是我不确定如何进行操作,因为我了解到使用.replace()会将新元素移动到页面的不同位置。 jQuery 的.replaceWith()行为非常理想。

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

1
再次使用jQuery有什么问题? - Ilia G
1
.replace() 是用于字符串的。请不要在 DOM 中使用它。您能更详细地描述一下您的问题吗?您是说您希望一个元素在出现时立即被替换,而不是等待整个 DOM 准备好吗? - user1106925
3个回答

9
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);

编辑后的演示


为什么要用 div?直接创建 input 会更快且代码更简洁。input = document.createElement('input'); input.type = "file"; input.id = input.name = "imagefiles"; - user1106925
@qwertymk 在 jsFiddle 上可以运行,但我的 Web 检查器在最后一行显示错误:"Uncaught SyntaxError: Unexpected token ILLEGAL"。 - technopeasant
2
@technopeasant:兄弟,你得多投票才能让更多人回答你啊,你问了128个问题,却只有11个投票? - qwertymk
@technopeasant:如果你从jsFiddle复制/粘贴代码,可能会带上一些看不见的非法字符。最好从这里复制代码。 - user1106925

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

0
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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接