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

如何用JavaScript将指定HTML标签包裹进div容器

解决方案

原生 JavaScript 实现

通过选中目标元素、创建容器、移动元素的步骤即可完成包裹:

// 选中所有需要包裹的元素
const passwordLabel = document.querySelector('label[for="plugin_delete_me_shortcode_password"]');
const passwordInput = document.getElementById('plugin_delete_me_shortcode_password');
const toggleCheckbox = document.getElementById('pw_3');
const toggleLabel = document.querySelector('label[for="pw_3"]');

// 创建父容器div,可按需添加类名/属性
const wrapperDiv = document.createElement('div');
wrapperDiv.classList.add('password-group');

// 将元素依次移入容器
wrapperDiv.appendChild(passwordLabel);
wrapperDiv.appendChild(passwordInput);
wrapperDiv.appendChild(toggleCheckbox);
wrapperDiv.appendChild(toggleLabel);

// 把容器插入到原元素所在位置(以密码输入框原位置为基准)
passwordInput.parentNode.insertBefore(wrapperDiv, passwordInput);

如果目标元素是连续排列的,也可以用更简洁的选择方式:

// 选中所有关联元素
const targetElements = document.querySelectorAll(
  '#plugin_delete_me_shortcode_password, ' +
  '#plugin_delete_me_shortcode_password ~ label[for="plugin_delete_me_shortcode_password"], ' +
  '#plugin_delete_me_shortcode_password + input, ' +
  '#plugin_delete_me_shortcode_password ~ label[for="pw_3"]'
);

const wrapper = document.createElement('div');
// 反向遍历避免节点移动导致的选择器失效
for (let i = targetElements.length - 1; i >= 0; i--) {
  wrapper.prepend(targetElements[i]);
}

// 将容器插入到原元素父节点中
targetElements[0].parentNode.appendChild(wrapper);

jQuery 实现

jQuery的wrapAll()方法专门用于将多个选中元素包裹到同一个父容器,写法更简洁:

// 选中所有目标元素,统一包裹进新div
$('label[for="plugin_delete_me_shortcode_password"], #plugin_delete_me_shortcode_password, #pw_3, label[for="pw_3"]')
  .wrapAll('<div class="password-group"></div>');

注意事项

  • 两种方法都会保留原元素的所有属性、事件绑定,不会破坏原有功能
  • 可根据需求给父容器添加class、id或其他属性,方便后续样式控制

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 07:54:18