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

如何将多个带content类的HTML元素替换为字符串形式的其他元素

实现方案

原生JavaScript实现

无需依赖第三方库,代码如下:

// 待替换的HTML字符串
const stringHtml = "<input type='text' />";
// 将匹配到的元素转为数组,避免DOM更新导致的遍历异常
const targetElements = Array.from(document.querySelectorAll('.content'));
targetElements.forEach(el => {
  // 直接修改outerHTML完成整段元素替换
  el.outerHTML = stringHtml;
});

jQuery实现

如果项目已引入jQuery,一行代码即可完成:

$('.content').replaceWith("<input type='text' />");

说明

上述代码会匹配页面所有带有content类的元素,不受元素标签类型、嵌套层级限制,会在原位置直接替换为指定的input元素。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 23:27:01