JS IF заявление, чтобы применить CSS, чтобы скрыть текст, если он найден на странице - PullRequest
0 голосов
/ 26 апреля 2018

Глядя, чтобы скрыть конкретный текст, когда / если это происходит, заполняется на странице.Не знаете, как это сделать

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 голосов
/ 26 апреля 2018

Вы можете использовать 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>

Чтобы сделать это при любой смене дома, вы можете использовать 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>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...