![](/img/trans.png)
[英]Navigate the “DOM” of a string as though it was html with AngularJS
[英]Scan DOM for a String in Angularjs
我正在寻找一种简单的方法来遍历Angularjs中给定字符串的DOM(或元素)。 如果找到给定的字符串,我想加粗它的文本。 我觉得我已经过度思考,因为我还没有提出解决方案。
例如
搜索狗应返回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>
任何想法或提示都会非常有用。 谢谢!
这将逻辑不加选择地应用于文档正文的整个innerHTML:
document.body.innerHTML = document.body.innerHTML.replace(/(dog)/gi, '<strong>$1</strong>');
我不会在有孩子的节点上这样做。 如果我搜索“div”会发生什么。 如果您想要更多地控制哪些节点,您可以只在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>')
});
见这里: https : //jsfiddle.net/kbLvdvh9/
这确实改变了DOM。 将带有类的跨度添加到这些节点可能更容易,因此您可以在搜索新单词时关闭突出显示。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.