AlexB AlexB - 3 months ago 14
HTML Question

How to wrap part of all text_node nodeValue in an html element?

I am iterating over all the text node in an html document in order to surround some words with a specific span.

Changing the

nodeValue
doesn't allow me to insert html. The
span
is escaped to be shown in plain text and I do not want that.

Here is what I have so far :



var elements = document.getElementsByTagName('*');

for (var i = 0; i < elements.length; i++) {
var element = elements[i];

for (var j = 0; j < element.childNodes.length; j++) {
var node = element.childNodes[j];

if (node.nodeType === Node.TEXT_NODE) {
node.nodeValue = node.nodeValue.replace(/Questions/, "<span>Questions</span>");
}
}
}

<p>Questions1</p>
<p>Questions 2</p>
<p>Questions 3</p>
<p>Questions 4</p>




Answer

I think that you need to recurse all the DOM and each match... have a look here:

function replacer(node, parent) { 
  var r = /Questions/g;
  var result = r.exec(node.nodeValue);
  if(!result) { return; }
  
  var newNode = this.createElement('span');
  
  newNode.innerHTML = node
    .nodeValue
    .replace(r, '<span class="replaced">$&</span>')
  ;
  
  parent.replaceChild(newNode, node);
}


document.addEventListener('DOMContentLoaded', () => {
  function textNodesIterator(e, cb) {
    if (e.childNodes.length) {
      return Array
        .prototype
        .forEach
        .call(e.childNodes, i => textNodesIterator(i, cb))
      ;
    } 

    if (e.nodeType == Node.TEXT_NODE && e.nodeValue) {
      cb.call(document, e, e.parentNode);
    }
  }

  document
    .getElementById('highlight')
    .onclick = () => textNodesIterator(
    document.body, replacer
  );
});
.replaced {background: yellow; }
.replaced .replaced {background: lightseagreen; }
.replaced .replaced .replaced {background: lightcoral; }
<button id="highlight">Highlight</button>
<hr>
<p>Questions1</p>
<p>Questions 2</p>
<p>Questions 3</p>
<p>Questions 4</p>
<p>Questions 5 Questions 6</p>
<div>
  <h1>Nesting</h1>
  Questions <strong>Questions 4</strong>
  <div> Questions <strong>Questions 4</strong></div>
  
  
  <div> 
    Questions <strong>Questions 4</strong>
    
  <div> Questions <strong>Questions 4</strong></div>
  </div>
</div>

Comments