gpt4 book ai didi

javascript - 如何替换 html 中不包括标签属性的文本?

转载 作者:行者123 更新时间:2023-11-28 00:43:04 28 4
gpt4 key购买 nike

我正在尝试在 HTML 中的公司名称旁边添加 TradeMark 符号 TM

使用下面的文字:

<sup>TM</sup>

&trade;

我有一个呈现的 HTML,我必须在其中添加商标符号。

HTML:

注意:我已经提到了 HTML 正文的一小部分

<div class="col-md-3">
<div class="logo"><img src="/wp-content/uploads/2017/02/logo.png"
onClick="window.location='https://www.walmart.com'"
alt="Walmart Inc" title="This is Walmart Inc for your help" style="pointer-events:all" />
</div></div>

<div class="submenu">
<a href="/blog" target="_blank">Walmart Inc Blog</a>
<a href="/blog" target="_blank">New Walmart Inc Products</a>
</div>
<meta itemprop="brand" content=" Walmart Inc"><p>Welcome to Walmart Inc.</p>

尝试了以下选项:

$("body").children().each(function () {
$(this).html($(this).html().replace(/Walmart Inc/g, "Walmart Inc&trade;"));
});

上面的选项替换了“HTML 标签属性的值”,即 alt,img 的标题,这是我不想要的。

$("body").children().each(function () {
$(this).html($(this).text().replace(/Walmart Inc/g, "Walmart Inc&trade;"));
});

& 这会导致从正文中删除所有 HTML 标签。

如何在替换时排除标签属性中的文本?

期望的输出:

<div class="col-md-3">
<div class="logo"><img src="/wp-content/uploads/2017/02/logo.png"
onClick="window.location='https://www.walmart.com'"
alt="Walmart Inc" title="This is Walmart Inc for your help" style="pointer-events:all" />
</div></div>

<div class="submenu">
<a href="/blog" target="_blank">Walmart Inc™ Blog</a>
<a href="/blog" target="_blank">New Walmart Inc™ Products</a>
</div>
<meta itemprop="brand" content=" Walmart Inc"><p>Welcome to Walmart Inc™.</p>

最佳答案

function insertTMAfter(name) {
document.querySelectorAll('*').forEach(function(item){
if(item.children.length == 0)
item.innerHTML = item.innerHTML.replace(name, name + "&trade;");
})
}

insertTMAfter("Stack Overflow");

// or in your case
insertTMAfter("Walmart Inc");

关于javascript - 如何替换 html 中不包括标签属性的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52276625/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com