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

如何用纯JS将div内的原有文本包裹到新增的del子元素中

问题根源

你的现有代码仅创建了空的<del>元素追加到.todo节点的子元素末尾,没有将原有的文本内容移动到<del>标签内部,因此原文本节点保留在原有位置,空<del>出现在文本后方。

实现代码

符合要求的原生JS实现如下:

const todo = document.querySelector('.todo')
const del = document.createElement('del')
// 提取原文本节点移动到del内部(DOM节点执行appendChild时若已存在于文档流中,会自动从原位置移除)
del.appendChild(todo.firstChild)
// 将带文本的del插入到todo中
todo.appendChild(del)

如果想要更严谨的写法,也可以用replaceChild直接替换原文本节点:

const todo = document.querySelector('.todo')
const del = document.createElement('del')
const originText = todo.firstChild
del.appendChild(originText)
todo.replaceChild(del, originText)

两种写法最终得到的结构都是<div class='todo'><del>abc</del></div>,全程没有用到innerHTML、行内样式或第三方库,符合你的练习要求。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 20:54:05