js if语句应用CSS隐藏文本,如果在页面上找到



希望在/如果碰巧在页面上填充特定文本。不确定如何执行此操作

var str = "Lease from 0%* or 0%*";
  if( str.search("e") > 0) { 
  //apply css to hide the above string if found on page
}

您可以使用 document.createTreeWalker获取所有文本小数,然后迭代它们,然后从nodeValue中删除文本。这将使文本保持在非文本上的位置(您可以替换e,并且<section>标签不会被弄乱,如果您有<div class="entity">或其他内容,则className也将保留:

function textNodesUnder(el){
  var n, a=[], walk=document.createTreeWalker(el,NodeFilter.SHOW_TEXT,null,false);
  while(n=walk.nextNode()) a.push(n);
  return a;
}
let nodes = textNodesUnder(document.body);
for (var i = 0; i < nodes.length; i++) {
    nodes[i].nodeValue = nodes[i].nodeValue.replace(/test/g, '');
}
.test {
    color: red;
}
<body>
    <div>This is a test</div>
    <span class="test">This is another test</span>
</body>

要在任何DOM更改上执行此操作,您可以使用MutationObserver并执行类似的操作(我将样式设置为color: red,但您将其设置为display: none

var MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;
let nodes = replaceTextUnder(document.body);
var observer = new MutationObserver(function(mutations) {
  observer.disconnect();
  mutations.forEach(function(mutation) {
     mutation.addedNodes.forEach(n => replaceTextUnder(n))
  });
  observer.observe(document.body, {
    attributes: true,
    childList: true,
    characterData: true,
    subtree: true  
   });
});
function replaceTextUnder(el){
  var n, a=[], walk=document.createTreeWalker(el,NodeFilter.SHOW_TEXT,null,false);
  while(n=walk.nextNode()) a.push(n);
  for (var i = 0; i < a.length; i++) {
    let index = a[i].nodeValue.indexOf('test');
    if (index !== -1) {
        let newNode = a[i].splitText(index);
        let span = document.createElement('span');
        span.style.color = 'red';
        span.appendChild(newNode);
        a[i].parentNode.insertBefore(span, a[i].nextSibling);
    }
  }
}
    
observer.observe(document.body, {
  attributes: true,
  childList: true,
  characterData: true,
  subtree: true  
 });
 
 let div = document.createElement('div');
 div.innerHTML = 'this is another test!';
 document.querySelector('.test').appendChild(div);
<body>
        <div>This is a test</div>
        <span class="test">This is another test</span>
    </body>

最新更新