You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何不使用insertBefore与jQuery将div作为lastElementChild插入?

How to Move/Insert a Div as a Parent's Last Element Child Without insertBefore or jQuery

Got it, let's break this down based on your existing DOM structure and needs. You have a parent container .s1 with children .box-1 through .box-4, and you want to manipulate an existing div (like .box-1) to become the parent's lastElementChild—no insertBefore, no jQuery required. Here are two clean vanilla JavaScript approaches:

Approach 1: Use appendChild() (Simplest for Moving Existing Elements)

The appendChild() method does double duty: if you pass an existing DOM element to it, it will automatically remove the element from its current position and append it to the end of the parent container, making it the new lastElementChild. This is perfect for your use case.

Code Example:

// Target the element you want to move
const box1 = document.querySelector('.box-1');
// Get its parent container
const s1 = box1.parentNode;

// Move box1 to the end of s1 (now the lastElementChild)
s1.appendChild(box1);

Why this works:

When you call appendChild() on an element that's already in the DOM, the browser doesn't create a duplicate—it just re-positions the existing element to the end of the parent. No extra methods needed, and it avoids insertBefore entirely.

Approach 2: Use insertAdjacentElement() (Flexible for Precise Placement)

If you ever need more granular control (like replicating your original behavior of inserting right before the current last element), insertAdjacentElement() is a great alternative. To make the element the lastElementChild, use the 'beforeend' position on the parent:

Code Example (Move to end as lastElementChild):

const box1 = document.querySelector('.box-1');
const s1 = box1.parentNode;

// Insert box1 at the end of s1 (becomes lastElementChild)
s1.insertAdjacentElement('beforeend', box1);

Replicate your original insertBefore behavior (insert before last element):

If you actually meant to place the element right before the current lastElementChild (matching your original code), you can target the last child directly and use the 'beforebegin' position:

const box1 = document.querySelector('.box-1');
const currentLastChild = document.querySelector('.s1').lastElementChild;

// Insert box1 right before the existing last element
currentLastChild.insertAdjacentElement('beforebegin', box1);

Final DOM Structure (After Moving to Last Position)

After running either approach to make .box-1 the lastElementChild, your DOM will look like this:

<div class="s1"> 
  <div class="box-2"></div> 
  <div class="box-3"></div> 
  <div class="box-4"></div> 
  <div class="box-1"></div> <!-- Now the lastElementChild -->
</div>

内容的提问来源于stack exchange,提问作者KAindex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:32:12