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

jQuery .after()实现替换而非追加及获取添加内容值的问题

解决方案

1. 替换已添加的'hi'为'hello'

直接添加纯文本节点的话,后续定位会比较麻烦,更稳妥的方式是给添加的内容套个容器(比如<span>),方便后续精准操作:

// 添加时用带类名的span包裹内容
$("#test").after('<span class="after-content">hi</span>');
// 后续直接通过类名找到元素并替换文本
$(".after-content").text("hello");

如果已经添加了无容器的纯文本节点,可以通过原生DOM的兄弟节点属性定位替换:

// 原添加代码
$("#test").after("hi");
$("#test").after("hello");
// 找到#test后的第一个文本节点,修改其内容
$("#test")[0].nextSibling.nodeValue = "hello";

2. 获取.after()添加的内容的值

根据添加内容的类型,有两种获取方式:

  • 添加纯文本节点时:
// 取#test后的第一个兄弟文本节点的值
const textValue = $("#test")[0].nextSibling.nodeValue;
console.log(textValue); // 输出'hi'(替换前)
  • 添加带容器的元素时:
// 取容器内的文本内容
const contentText = $(".after-content").text();
// 若要获取HTML结构,用html()方法
const contentHtml = $(".after-content").html();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 15:40:23