[英]Scan DOM for a String in Angularjs
I'm looking for a simple way to traverse a DOM (or element) for a given string in Angularjs. 我正在寻找一种简单的方法来遍历Angularjs中给定字符串的DOM(或元素)。 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 搜索狗应返回4个结果
<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: 这将逻辑不加选择地应用于文档正文的整个innerHTML:
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”. 如果我搜索“div”会发生什么。 If you want more control over which nodes, you can do that replace regex on the innerHTML specific nodes only, simple example: 如果您想要更多地控制哪些节点,您可以只在innerHTML特定节点上替换正则表达式,简单示例:
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/ 见这里: https : //jsfiddle.net/kbLvdvh9/
This does alter the DOM. 这确实改变了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. 将带有类的跨度添加到这些节点可能更容易,因此您可以在搜索新单词时关闭突出显示。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.