最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin4浏览0评论

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' />");

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' />");
Share Improve this question asked Apr 15, 2012 at 19:24 technopeasanttechnopeasant 7,93933 gold badges93 silver badges151 bronze badges 2
  • 1 What is the problem with using jQuery again? – Ilia G Commented Apr 15, 2012 at 19:27
  • 1 .replace() is for strings. Please don't use it for DOM. Could you describe your issue a little better? Are you saying you want an element to be replaced as soon as it appears, and not wait for the rest of the DOM to be ready? – user1106925 Commented Apr 15, 2012 at 19:28
Add a comment  | 

3 Answers 3

Reset to default 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);

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

  const node = new DOMParser().parseFromString(html, 'text/html').body.childNodes[0];
  document.getElementById(id).replaceWith(node);
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

发布评论

评论列表(0)

  1. 暂无评论