Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

best way to write jQuery's replaceWith() in natural JavaScript

Having trouble with a function hitting the page as soon as possible, so i need to write it in pure javascript and include it in the head. not sure how to go about it, because as i understand it, by using .replace() the new element will be moved to a different location on the page. jQuery's replaceWith() behavior is ideal.

$("#imagefiles").replaceWith("<input type='file' name='imagefiles' id='imagefiles' />");
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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


EDIT as per am not i am:

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...