Aidin Azari Aidin Azari - 6 months ago 30
jQuery Question

How to replace contents of parent element, ignoring children using jQuery

I have some HTML like this:

<div id="demo">
<p>
<span class="myClass">Word test should not be marked</span>
Word test should be marked<br />
</p>
</div>


How can I find a word ('test') inside the
div
excluding the
span
and mark it using jQuery? I have seen a lot of solutions in SO, etc. but none of them worked for me. FYI the code I'm trying to use is something like this :

var regex = XRegExp('test', 'i');
$('#demo').markRegExp(regex);

Answer

Get all child nodes using contents() and then iterate and update the text nodes.

$('#demo p')
  .contents() // get all child nodes including text and comment nodes
  .each(function() { // iterate over nodes
    if (this.nodeType == 3) // check node is text node
      $(this).replaceWith(this.textContent.replace(/test/g, '<span class="test">$&</span>')) // update the content and replace node with html content
  });
.test {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="demo">
  <p>
    <span class="myClass">Word test should not be marked</span>
    Word test should be marked
    <br />
  </p>
</div>