Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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' />");
like image 462
technopeasant Avatar asked Apr 15 '12 19:04

technopeasant


2 Answers

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

like image 165
qwertymk Avatar answered Oct 17 '22 10:10

qwertymk


  const node = new DOMParser().parseFromString(html, 'text/html').body.childNodes[0];
  document.getElementById(id).replaceWith(node);
like image 26
Diego Carrion Avatar answered Oct 17 '22 11:10

Diego Carrion