jquery – 搜索字符串然后搜索样式

我需要使用jQuery搜索文档来查找特定单词.它实际上是一个品牌名称,无论在何处使用,都必须是粗体和斜体.

我可以使用:包含但仅基于单个元素.我需要能够通过锚点,列出div等.

$( "a:contains('brand name')" ).html().replace('brand name'....

任何想法,将不胜感激.

更新:
我已经实现了这个目的,并取代了页面上的所有内容,但我现在需要用一个类包装.如此接近但却难以接受这一个.再次提出一个想法将不胜感激.

$("body *").contents().each(function() {
  if(this.nodeType==3){
    this.nodeValue = this.nodeValue.replace(/brandname/g,'colour');

  }
});

解决方法

您可以使用文档片段替换textNodes.这允许您对文本和样式化节点进行分组,并将其与现有textNode交换.
var x = 0;
$("body *").contents().each(function() {

   if (this.nodeType == 3 && this.parentElement.tagName != "SCRIPT") {

     var text = this.nodeValue;
     var i = 0,lastIndex = 0;
     var search = /brandname/ig;
     var result;
     var parent = this.parentNode;
     var textNode = null;
     var highlight = null;
     var textRange = "";
     var fragment = document.createDocumentFragment();

     // Do search
     while ((result = search.exec(text)) !== null) {
    
       // add plain text before match
       textRange = text.substring(lastIndex,result.index);
       if (textRange != '') {
         textNode = document.createTextNode(textRange);
         fragment.appendChild(textNode);
       }
       
       // add highlight elements
       highlight = document.createElement('span');
       highlight.innerHTML = result[0];
       highlight.className = "hi";
       fragment.appendChild(highlight);
       lastIndex = search.lastIndex;
     }

     // Add trailing text
     textRange = text.substring(lastIndex);
     if (textRange != '') {
       textNode = document.createTextNode(textRange);
       fragment.appendChild(textNode);
     }
     
     // Replace textNode with our text+highlight
     if(fragment.children.length > 0) {
       this.parentNode.replaceChild(fragment,this);
     }
   }

 });
span.hi {
  background-color: #FFCC00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
  Hello world this is my brandname. The BrAnDNAMe is regex matched and we can change subelements like "<a href=''>Brandname</a>." It should not replace <b>elements</b> that don't match.
</p>

相关文章

页面搜索关键词突出 // 页面搜索关键词突出 $(function () {...
jQuery实时显示日期、时间 html: &lt;span id=&quot...
jQuery 添加水印 &lt;script src=&quot;../../../.....
中文:Sys.WebForms.PageRequestManagerParserErrorExceptio...
1. 用Response.Write方法 代码如下: Response.Write(&q...
Jquery实现按钮点击遮罩加载,处理完后恢复 思路: 1.点击按...