Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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

Solution 2:

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

Solution 3:

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

Years later. There is now an childNode.replaceWith() but it is not strictly equivalent to the JQuery replaceWith(); Nor is it compatible with I.E.

The above code creates a document fragment from the given HTML, and inserts it after the original element in the DOM and then deletes the original element, effectively replacing it.

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

Post a Comment for "Best Way To Write Jquery's Replacewith() In Natural Javascript"