Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML Shadow dom: why does attachShadow(...).insertAdjacentHTML not work but attachShadow(...).innerHTML work?

Why do the following two work:

document.body.innerHTML = '<div>Test1</div>';

document.body.insertAdjacentHTML('beforeEnd', '<div>Test2</div>');

and this also works:

document.body.attachShadow({mode: 'open'}).innerHTML = '<div>Test3</div>';

But following doesn't work:

document.body.attachShadow({mode: 'open'}).insertAdjacentHTML('beforeEnd', '<div>Test4</div>');

It gives error Uncaught TypeError: document.body.attachShadow(...).insertAdjacentHTML is not a function

https://jsfiddle.net/uzdy3fv9/

like image 419
sudoExclaimationExclaimation Avatar asked Oct 22 '25 03:10

sudoExclaimationExclaimation


1 Answers

When you do

document.body.innerHTML = '<div>Test1</div>';
document.body.insertAdjacentHTML('beforeEnd', '<div>Test2</div>');

you are invoking methods on Element.prototype.

Shadow roots aren't element - they're similar in some respects, but they're not the same. Shadow roots have certain methods/properties, including .innerHTML, but not including .insertAdjacentHTML.

(which makes sense... what would .insertAdjacentHTML('afterend' or 'beforebegin' even mean with a shadow root? The shadow root is not part of a container)

like image 96
CertainPerformance Avatar answered Oct 24 '25 16:10

CertainPerformance