7

This is sort of a continuation of an earlier question.

I have some html.

<h3>things that are red:</h3>
<ul>
   <li><a href="html://www.redapples.com">Red Apples</a></li>
   <li><a href="html://www.redmeat.com">Red Meat</a></li>
   <li><a href="html://www.redcar.com">All Red Cars</a></li>
</ul>

I want to use javascript to wrap all of the text elements with a element

The result I am looking for.

<h3>things that are <span class="red">red</span>:</h3>
<ul>
   <li><a href="html://www.redapples.com"><span class="red">Red</span> Apples</a></li>
   <li><a href="html://www.redmeat.com"><span class="red">Red</span> Meat</a></li>
   <li><a href="html://www.redcar.com">All <span class="red">Red</span> Cars</a></li>
</ul>

After a lot of thought I realized that I had to distinguish between text nodeTypes and Element NodeTypes while navigating the DOM. I used some of the feedback from my earlier question, and wrote this little script.

function walkTheDOM(node, func) {
    func(node);
    node = node.firstChild;
    while (node) {
        walkTheDOM(node, func);
        node = node.nextSibling;
    }
}

walkTheDOM(document.body, function (node) {
// Is it a Text node?       
if (node.nodeType === 3) { 
    var text = node.data.trim();
    // Does it have non white-space text content?       
    if (text.length > 0) {              
        node.data = text.replace(/(RED)/gi, '<span class="red">$1</span>'); 
    }
}
});

This does pretty much what I want it to do, except the output is text rather than html. So my question is this, is there an easy way to fix this line

node.data = text.replace(/(RED)/gi, '<span class="red">$1</span>'); 

So that the output is html?

Community
  • 1
  • 1
increase Mather
  • 139
  • 2
  • 6
  • 1
    `node.innerHTML = text.replace...` Shouldn't have been very difficult to research this yourself – charlietfl Sep 16 '14 at 01:35
  • @charlietfl: That will break for `
  • >/li< bug
  • `, for example, unless you make sure to reencode things. `document.createElement` way is safer (but definitely more cumbersome). – Amadan Sep 16 '14 at 01:37
  • 1
    Are you sure the innerHTML is an object at this level? I've tried adding it, and I get nothing. – increase Mather Sep 16 '14 at 01:45
  • 1
    @charlieftl Yeah, innerHTML isn't a property of Text Objects. So the question remains, is there an easy way convert a text object into an html object. – increase Mather Sep 16 '14 at 01:53