简体   繁体   中英

Can I use insertAdjacentHTML to insert DOM element

insertAdjacentHTML expects 2 arguments:

  • position ( "beforebegin" , "afterbegin" , "beforeend" , "afterend" )
  • html (will be converted from text to DOM)

Can I pass DOM element as the second argument?

For insertAdjacentHTML , the documentation clearly states that the first argument must be of type string

element.insertAdjacentHTML(position, text);

position is the position relative to the element, and must be one of the following strings :
"beforebegin", "afterbegin", "beforeend", "afterend"

It's not very clear about what the second argument can be, but testing shows that toString() is executed internally on the second argument, so the answer is

yes , you can in most cases pass a DOM element as the second argument, but the real answer is no , it won't be appended to the page, instead you'll just get the string

[object HTMLDivElement]

as the DOM element is converted to a string, and that means the function always expects the second argument to be a valid string of HTML, not a DOM element.

Here's a quick test

 var d1 = document.getElementById('one'); var d3 = document.createElement('div'); d3.innerHTML = 'three'; d1.insertAdjacentHTML('afterend', '<div id="two">two</div>'); d1.insertAdjacentHTML('afterend', d3); 
 <div id="one">one</div> 

There are other methods available that are much more suitable for actual DOM elements, for instance appendChild , insertBefore etc.

Which one to use depends on where the element is to be inserted etc, but inserting in the same place as the four options available in insertAdjacentHTML is possible, and generally not very hard to do.

There's also Element.insertAdjacentElement() which works exactly like insertAdjacentHTML , but accepts a DOM node instead of a string of HTML.

While you can't pass a DOM element directly, it's possible to pass element.outerHTML to feed insertAdjacentHTML 's second parameter with it's HTML string representation.

Example:

const parent = document.querySelector('.parent');
const child = document.createElement('p');

child.innerHTML = 'Awesome!';
parent.insertAdjacentHTML('beforeend', child.outerHTML);

// <div class="parent">
//   <p>Awesome!</p>
// </div>

.insertAdjacentHTML() only accept string that will be parsed as HTML and inserted (like innerHTML )

To insert DOM element you can use .insertAdjacentElement()

MDN: https://developer.mozilla.org//docs/Web/API/Element/insertAdjacentElement

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM