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

tec*_*ant 6 javascript jquery load replacewith

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

$("#imagefiles").replaceWith("<input type='file' name='imagefiles' id='imagefiles' />");
Run Code Online (Sandbox Code Playgroud)

qwe*_*ymk 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);
Run Code Online (Sandbox Code Playgroud)

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);
Run Code Online (Sandbox Code Playgroud)

编辑了DEMO

  • @technopeasant:老兄,你得多投票让人们回答你,当你问128个问题时,你总是11票? (2认同)