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

如何使用jQuery/原生JS清空div子元素文本且不删除DOM结构

实现方案

原生JS实现

核心逻辑是递归遍历目标元素下的所有节点,仅清空文本节点(nodeType === 3)的内容,保留所有元素节点的结构和属性不变。

// 封装清空文本的通用函数
function clearAllText(parentNode) {
  const childNodes = parentNode.childNodes;
  for (let i = 0; i < childNodes.length; i++) {
    const currentNode = childNodes[i];
    // 文本节点直接清空内容
    if (currentNode.nodeType === Node.TEXT_NODE) {
      currentNode.textContent = '';
    } 
    // 元素节点递归处理子节点
    else if (currentNode.nodeType === Node.ELEMENT_NODE) {
      clearAllText(currentNode);
    }
  }
}

// 调用示例
clearAllText(document.getElementById('student_profile'));

jQuery实现

可以封装为jQuery插件方便调用:

// 封装jQuery插件
$.fn.clearInnerText = function() {
  return this.each(function() {
    $(this).contents().each(function() {
      if (this.nodeType === Node.TEXT_NODE) {
        this.textContent = '';
      } else if (this.nodeType === Node.ELEMENT_NODE) {
        $(this).clearInnerText();
      }
    });
  });
};

// 调用示例
$('#student_profile').clearInnerText();

原方法失效的原因

  • $().html('') 会直接移除目标元素下的所有子节点,替换为空字符串,自然会丢失所有子元素结构
  • $().text('') 会把目标元素下的所有子节点替换为单个空文本节点,也会删除所有子元素

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 18:27:07