3

I'm looking for a simple way to traverse a DOM (or element) for a given string in Angularjs. If the given string is found, I'd like to bold it's text. I feel I'm overthinking this already since I haven't come up with a solution yet.

For example

Searching for Dog should return 4 results

<section id="container">
  <div>
    <h2>Dogs are great</h2>
    <p>They are the best. Everyone should have a dog</p>
    <div>
      <p>Cat owners are just confused dog owners</p>
      <p>What's your doggos name?</p>
    </div>
  </div>
</section>

<script>
$scope.search = function(word){
    var entireDom = // Get the entire innerText of the <section>
    if(entireDom.match(word) {
      // Wrap the string in <strong> tags & update the DOM somehow?
      // This function should probably be case insensitive
    }
}
<script>

Any ideas or tips would be super helpful. Thanks!

1

1 Answer 1

1

This applies that logic indiscriminately to the entire innerHTML of the body of a document:

document.body.innerHTML = document.body.innerHTML.replace(/(dog)/gi, '<strong>$1</strong>');

I would not do this on nodes with children though. What happens if I search for “div”. If you want more control over which nodes, you can do that replace regex on the innerHTML specific nodes only, simple example:

Array.prototype.slice.call(document.body.getElementsByTagName("*"))
  .forEach(f => {
    if(f.children.length === 0) f.innerHTML = f.innerHTML.replace(/(dog)/gi, '<strong>$1</strong>')
  });

See here: https://jsfiddle.net/kbLvdvh9/

This does alter the DOM. It might be easier to add a span with a class to those nodes so you can turn the highlight off when searching for a new word or something.

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

2 Comments

Thanks Jorg. This is a perfect solution. Could you advise how to pass a variable as the first argument in replace() function? It's tricky with the slashes & gi involved
You’ll need to use the Regexp class, you’ll find documentation and answers on that elsewhere.

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.