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

javascript - What is the difference between insertAdjacentHtml and insertAdjacentElement? - Stack Overflow

programmeradmin1浏览0评论

What is the main difference between element and html? I used
insertAdjacentElement('beforeend', html);
and it showed error. But worked when using
insertAdjacentHTML('beforeend', html);
Just wondering what the difference was.

What is the main difference between element and html? I used
insertAdjacentElement('beforeend', html);
and it showed error. But worked when using
insertAdjacentHTML('beforeend', html);
Just wondering what the difference was.

Share Improve this question asked Jul 19, 2019 at 10:59 Sack32Sack32 531 silver badge3 bronze badges 4
  • 1 The former inserts an existing DOM element, and the latter creates the elements to insert from the HTML code that gets passed to it. – misorude Commented Jul 19, 2019 at 11:04
  • MDN insertAdjacentHTML MDN insertAdjacentElement – Yury Tarabanko Commented Jul 19, 2019 at 11:05
  • Your error probably occurred because insertAdjacentElement expects a reference to an existing HTML element, while insertAdjacentHTML can accept any valid HTML (or XML) markup. See the MDN articles ( Yury Tarabanko linked to them above) for details -- which is good advice for pretty much any web-development question :) – Cat Commented Jul 19, 2019 at 11:13
  • BTW, to make an "actual" element suitable for use with insertAdjacentElement, you can use the createElement method. For example, const newDiv = document.createElement("div"). – Cat Commented Jul 19, 2019 at 11:21
Add a ment  | 

2 Answers 2

Reset to default 8

insertAdjacentElement() is used to insert an element which is already in the Dom. You can get this element with getElementById() for example. https://www.w3schools./jsref/met_node_insertadjacentelement.asp

insertAdjacentHtml() is used to insert html code. https://www.w3schools./jsref/met_node_insertadjacenthtml.asp

The insertAdjacentElement method is only patible with either elements already present in the DOM or new elements created with document.createElement method. The insertAdjacentHTML however will not work when you are trying to insert DOM elements into another but rather works on strings that can be parsed as XML or HTML which is then added to the parent container.

Although they are pretty similar in that they have more positioning parameters than node.appendchild and element.append methods

发布评论

评论列表(0)

  1. 暂无评论