JS IF statement to apply CSS to hide text if found on page

139
April 26, 2018, at 12:36 PM

Looking to hide specific text when/if it happens to get populated on a page. Unsure of how to do this

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

You could use document.createTreeWalker to get all of the textNodes, then iterate through them and remove the text from the nodeValue. This will keep the text in non textNodes in place (you can replace e and your <section> tag won't get messed up, and if you have <div class="entity"> or something, the className will remain as well:

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>

To do it on any dom change, you could use a MutationObserver and do something like this (where I am setting the style to color: red, but you would set it to 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>

READ ALSO
Foundation tabs content transition slide

Foundation tabs content transition slide

While using foundation's tabs what would be the best way to transition the content so it looked like it was sliding left or right? JQuery, MotionUI, or any other ideas?

156