insertAdjacentElement Hits Four Positions
Place nodes precisely with insertAdjacentElement: beforebegin, afterbegin, beforeend, and afterend hit all four sides of a target element.
Code
// insertAdjacentElement:四个命名位置,精确插到目标节点的相对处
const list = document.createElement('ul');
const target = document.createElement('li');
target.textContent = 'B';
list.append(target);
// beforebegin / afterbegin:目标外侧上方与内侧顶端
const a = document.createElement('li');
a.textContent = 'A';
target.insertAdjacentElement('beforebegin', a);
const b = document.createElement('li');
b.textContent = 'B2';
target.insertAdjacentElement('afterbegin', b);
// beforeend / afterend:目标内侧末尾与外侧下方
const c = document.createElement('li');
c.textContent = 'B3';
target.insertAdjacentElement('beforeend', c);
const d = document.createElement('li');
d.textContent = 'D';
target.insertAdjacentElement('afterend', d);
console.log(list.children.length, 'items');
console.log([...list.children].map((li) => li.textContent).join(' '));Inside the snippet
Top-level bindings list, target hold the demo state — nothing sits inside a function scope.
What to watch for
- The snippet leans on
document— browser-only surfaces a bare Node process cannot provide.
Key statements
target.insertAdjacentElement('beforebegin', a);
target.insertAdjacentElement('afterbegin', b);
target.insertAdjacentElement('beforeend', c);
Interactive Tools for This Topic
FAQ
- Does insertAdjacentElement Hits Four Positions run in plain Node.js?
- No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.
Report a problem with this exampleOpens a pre-filled issue on GitHub.