如果在页面上找到,则应用CSS来隐藏文本的JS IF语句

时间:2018-04-25 21:04:10

标签: javascript css string if-statement

当/恰好在页面上填充时,希望隐藏特定文本。不确定如何做到这一点

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

1 个答案:

答案 0 :(得分:1)

您可以使用document.createTreeWalker获取所有textNodes,然后遍历它们并从nodeValue中删除文本。这会将文本保留在非textNodes中(您可以替换e,并且您的<section>标记不会搞砸,如果您有<div class="entity">或其他内容,则为className将保持不变:

&#13;
&#13;
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, '');
}
&#13;
.test {
    color: red;
}
&#13;
<body>
    <div>This is a test</div>
    <span class="test">This is another test</span>
</body>
&#13;
&#13;
&#13;

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

&#13;
&#13;
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);
&#13;
<body>
        <div>This is a test</div>
        <span class="test">This is another test</span>
    </body>
&#13;
&#13;
&#13;