如何在html中替换标记属性以外的文本?

时间:2018-09-11 13:03:29

标签: javascript jquery html

我正在尝试在HTML中的公司名称旁边添加商标标记 TM

在文本下方使用

<sup>TM</sup>

OR

&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>

2 个答案:

答案 0 :(得分:1)

// Doesn't work
import { chance as Chance.Chance() } from 'chance';

答案 1 :(得分:0)

仅针对文本节点并且仅使用更新的html替换特定文本节点的方法。不会影响诸如alt, title etc

之类的属性

这将优于替换较大的html块(可能会导致事件监听器丢失),因为您仅替换文本而没有该文本的父元素

var term = "Walmart Inc";

$('body *:contains("' + term + '")')
  .not(':has(:contains("' + term + '"))')
  .contents().each(function() {
    // nodeType for text nodes is 3
    if (this.nodeType === 3 && this.textContent.includes(term)) {
      var html = this.textContent.replace(term, term + '&trade;')
      // replace text node with html
      $(this).replaceWith(html)
    }

  })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<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>