ncesar
ncesar

Reputation: 1802

How to change a specific element innerHTML with querySelectorAll('*')

I'm trying to build a code that will search through an entire page for a specific word and if it finds this word, it is supposed to change the dom of the found element. With my current code I'm able to find the element but when I change the innerHTML, it is changing all the page content.

How can I only change the innerHTML of the elements with the word JavaScript?

var nodes = document.querySelectorAll('*');
for (var i = 0; i < nodes.length; i++) {
    if(nodes[i].innerHTML.indexOf('JavaScript') !== -1) {
       console.log(typeof nodes[i]);
       nodes[i].innerHTML = 'text changed';
    }
}

I know that the problem is because I'm targetting all the nodes, and for this reason, it is changing all the HTML. How can I prevent that and only change elements that matches JavaScript?

Upvotes: 0

Views: 708

Answers (1)

MBadrian
MBadrian

Reputation: 409

hi when you use nodes[i].innerHTML.indexOf('JavaScript') this your <body> and <html> has this word in innerHTML then change your document but i add new condition to if like this nodes[i].innerHTML.indexOf('<') == -1 that say only in child node find this string and in parent node don't check

var nodes = document.querySelectorAll('*');
for (var i = 0; i < nodes.length; i++) {
console.log(nodes[i].innerHTML.indexOf('<'))
    if(nodes[i].innerHTML.indexOf('JavaScript') != -1 && nodes[i].innerHTML.indexOf('<') == -1 ) {
       console.log(typeof nodes[i]);
       nodes[i].innerHTML = 'text changed';
    }
}
<div>
  <p>hello <span>JavaScript</span></p>
  <h1>hello World!</h1>
</div>

Upvotes: 1

Related Questions