Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 618
AlexB Avatar asked Aug 06 '16 07:08

AlexB


1 Answers

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>
like image 61
Hitmands Avatar answered Nov 04 '22 03:11

Hitmands