-2

I should write an extension that can change a color for a word in web page, this code can replace words but can't change their background color

See below code : 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

How to apply <span class="red"> for pineapple?

4
  • It's unclear what your are asking here please refer to Ask New Question and ask your question correctly Commented Feb 28, 2018 at 13:23
  • @bRIMOs i changed question Commented Feb 28, 2018 at 13:42
  • not sure about your question. do you have a class named red in your file? if not then create it, otherwise apply directly here like <span style="color:red">Pineapple</span> Commented Mar 1, 2018 at 5:38
  • Does this answer your question? Replace a textNode with HTML text in Javascript? Commented May 24, 2023 at 14:53

3 Answers 3

2

because of you're accessing a TextNode not a HTML node the replaced text will be a text and not parsed as html

So just access your element as Html node (node.nodeType == 1 ) Node.ELEMENT_NODE (see in doc ) , then get it's innerHTML and replace it with new innerHTML

See below Snippet :

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>

Also Fiddle

Sign up to request clarification or add additional context in comments.

3 Comments

This works great, except that attributes in the htmlnode also get replaced. <span data-word="Apple">This is an Apple</span>. How would you prevent that?
Hm, on second thought, this just parses the entire BODY element at once instead of parsing each individual DOM element.
@Kokodoko You're right , I'll try find other solution for that ,!
0

If you put HTML into a nodeValue it will be escaped. Try:

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

1 Comment

+i can't :( my reputation 11 when i get 15 i upvote your comment)
0

I don't like textNodes in my code and I normalize everything to span elements like this:

// text-nodes-to-span.js v1
function textNodesToSpan(elements, recursive) {
    recursive = recursive || true;
    if (!('length' in elements)) { // to array
        elements = [elements];
    };
    for (let node of elements) {
        if (node.nodeType === 3) {
            let span = document.createElement('span');
            span.textContent = node.textContent;
            node.parentElement.insertBefore(span, node);
            node.remove();
        } else if (recursive) {
            textNodesToSpan(node.childNodes);
        };
    };
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.