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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With