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

用原生JavaScript实现多元素包裹新div,替代jQuery DOM操作

原生JavaScript实现jQuery的nextAll + wrapAll逻辑

这是个很实用的DOM操作场景,我们可以完全用原生API实现和你那段jQuery代码一致的效果,而且全程直接操作DOM节点,避免了截取/拼接HTML字符串的繁琐(还能保留元素上绑定的事件、数据属性等,比innerHTML方式更健壮)。

完整实现代码(对应jQuery的each逻辑,支持多个.blue元素)

// 获取页面中所有.blue元素
const blueElements = document.querySelectorAll('.blue');

blueElements.forEach(blueEl => {
  // 收集当前.blue元素之后的所有同级元素
  let nextSibling = blueEl.nextElementSibling;
  const siblingsToWrap = [];

  // 循环遍历后续所有兄弟节点,注意要先暂存下一个节点(移动后原节点的nextSibling会变化)
  while (nextSibling) {
    const temp = nextSibling.nextElementSibling;
    siblingsToWrap.push(nextSibling);
    nextSibling = temp;
  }

  // 如果有需要包裹的元素,才创建wrapper
  if (siblingsToWrap.length > 0) {
    // 创建wrapper容器并添加类名
    const wrapper = document.createElement('div');
    wrapper.classList.add('wrapper');

    // 将收集到的元素移入wrapper(appendChild会自动把节点从原位置移除)
    siblingsToWrap.forEach(el => wrapper.appendChild(el));

    // 把wrapper插入到当前.blue元素的后面
    blueEl.after(wrapper);
  }
});

代码逻辑对应关系

  • document.querySelectorAll('.blue') 对应jQuery的 $(".blue")
  • forEach 对应jQuery的 .each()
  • 用nextElementSibling循环收集后续元素,对应jQuery的 .nextAll()
  • 创建wrapper容器并移动节点的逻辑,对应jQuery的 .wrapAll('<div class="wrapper"></div>')

简化版(如果页面中只有一个.blue元素)

如果你的场景里确定只有一个.blue元素,可以简化代码,去掉遍历逻辑:

const blueEl = document.querySelector('.blue');
if (blueEl) {
  const wrapper = document.createElement('div');
  wrapper.classList.add('wrapper');

  let nextSibling = blueEl.nextElementSibling;
  // 直接把后续元素移入wrapper
  while (nextSibling) {
    const temp = nextSibling.nextElementSibling;
    wrapper.appendChild(nextSibling);
    nextSibling = temp;
  }

  // 只有当wrapper里有元素时才插入
  if (wrapper.children.length > 0) {
    blueEl.after(wrapper);
  }
}

这个方案的优势在于完全基于DOM节点操作,不会破坏元素原有的状态(比如事件监听器、自定义属性),和jQuery的实现逻辑保持一致,同时不需要依赖任何库。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:24:33