用HTML span内容替换Text Node

时间:2018-02-28 13:21:17

标签: javascript jquery html regex google-chrome-extension

我应该写一个可以改变网页中单词颜色的扩展名,这段代码可以替换单词,但不能改变它们的背景颜色

见下面的代码: 的 content.js

walk(document.body);

function walk(node)  
{

    var child, next;

    switch ( node.nodeType )  
    {
        case 1: 
        case 9:  
        case 11: 
            child = node.firstChild;
            while ( child ) 
            {
                next = child.nextSibling; 
                walk(child);
                child = next;
            }
            break;

        case 3: 
            handleText(node);
            break;
    }
}

function handleText(textNode) 
{
    var v = textNode.nodeValue;

    v = v.replace(/Apple/gi, '<span class="red">Pineapple</span>');

    textNode.nodeValue = v;
}

Image

如何将<span class="red">应用于菠萝?

2 个答案:

答案 0 :(得分:2)

因为您正在访问TextNode而不是HTML节点,所替换的文本将是文本而不会被解析为html

所以只需将您的元素作为Html节点(node.nodeType == 1Node.ELEMENT_NODE访问(请参阅doc),然后获取innerHTML并将其替换为新innerHTML }

见下面的摘录:

walk(document.body);

function walk(node) {

  var child, next;
  switch (node.nodeType) {

    case 1:
      handleText(node);
      break;
    case 9:
    case 11:
      child = node.firstChild;
      while (child) {
        next = child.nextSibling;
        walk(child);
        child = next;
      }
      break;

    case 3:
      break;
  }
}

function handleText(node) {
  var v = node.innerHTML;
  v = v.replace(/Apple/gi, '<span class="red">Pineapple</span>');
  node.innerHTML = v;
}
.red {
  color: red;
  font-weight: bold;
}
<div>
  Apple dsqd sqd qsd Apple sqd sqd Apple
  <p>Apple is an apple and it's an apple </p>
  <p><span>Apple also is an PeanApple</span></p>
  <div>
    what you think about
    <p>
      Apple now !
    </p>
  </div>
</div>

另外Fiddle

答案 1 :(得分:0)

如果将HTML放入nodeValue,它将被转义。尝试:

textNode.parentElement.innerHTML = 'This <strong>accepts</strong> HTML';