2

i have this code that finds a word in the entire body of a html page

var word = "active",
    queue = [document.body],
    curr
;
while (curr = queue.pop()) {
    if (!curr.textContent.match(word)) continue;
    for (var i = 0; i < curr.childNodes.length; ++i) {
        switch (curr.childNodes[i].nodeType) {
            case Node.TEXT_NODE : // 3
                if (curr.childNodes[i].textContent.match(word)) {
                    console.log("Found!");
                    console.log(curr);
                    // you might want to end your search here.
                    word.replace('active', 'test');
                }
                break;
            case Node.ELEMENT_NODE : // 1
                queue.push(curr.childNodes[i]);
                break;
        }
    }
}

And what i'm trying to do is if active is found, replace it with something else but i have tried some ways and i wasnt able to do it. What i'm doing wrong?

ncesar
  • 1,592
  • 2
  • 15
  • 34
  • 1
    `word.replace('active', 'test');` replaces the `active` found in variable `word` with `test` and returns (which you've discarded) the changed text ... i.e. that line of code does nothing useful ... you need to change the text inside `.textContent` – Jaromanda X Mar 30 '19 at 00:50
  • 1
    `curr.childNodes[i].textContent = curr.childNodes[i].textContent.replace(word, 'test');` – Jaromanda X Mar 30 '19 at 00:51
  • 1
    Possible duplicate of [Replace words in the body text](https://stackoverflow.com/questions/5558613/replace-words-in-the-body-text) – Heretic Monkey Mar 30 '19 at 00:52

1 Answers1

1

This would give the result you are looking for (I decided to skip of 'SCRIPT' nodeName's so you do not accidentally modify any code:

let word = "active";
let queue = [document.body];
let curr;

while (curr = queue.pop()) {
  if (!curr.textContent.match(word) || curr.nodeName === 'SCRIPT') continue;
  for (var i = 0; i < curr.childNodes.length; ++i) {
    if (curr.childNodes[i].nodeName === 'SCRIPT') continue;
    switch (curr.childNodes[i].nodeType) {
      case Node.TEXT_NODE: // 3
        if (curr.childNodes[i].textContent.match(word)) {
          console.log("Found!", `'${curr.childNodes[i].textContent}'`);
          curr.childNodes[i].textContent = curr.childNodes[i].textContent.replace('active', 'test');
        }
        break;
      case Node.ELEMENT_NODE: // 1
        queue.push(curr.childNodes[i]);
        break;
    }
  }
}
<div>asdf</div>
<span>active</span>
<div>asdf</div>

Hope this helps,

Miroslav Glamuzina
  • 4,472
  • 2
  • 19
  • 33