0

In all the possible answers in SO, they also change the attributes.

<div id="content">
  <a href="foo.com/first-foo/method">The foo method</a>
  <h1>the foo.</h1>
  <p>While the foo is red</p>
  <div class="_special-foo">
   Some other foo, might not be foo.
  </div>
</div>
<script>
 let theFoo = document.getElementById('content').innerHTML;
 document.getElementById('content').innerHTML = theFoo.replace(/foo/g, 'Foo');
</scrip>

That is changing all foo to Foo, is okay but not, because it also changes the href, class and/or possible id's, I haven't found any pattern. In most cases, if not changing the href, it will change the class, if not, then it missed some . or , after in other cases will miss the whole thing.
So how to replace just string without touching/changing class, id, href attributes.?
Thank you.

Robert Bradley
  • 548
  • 2
  • 21
Tanker
  • 1,178
  • 3
  • 16
  • 49
  • 1
    You need to iterate over all the text nodes, just replacing them, rather than assigning the innerHTML of the whole thing. – Barmar Nov 08 '22 at 17:51
  • Could you please elaborate, instead of using `.innerHTML` I should use `.innerTEXT` ? – Tanker Nov 08 '22 at 18:01
  • 1
    @Tanker Have you seen [this answer](/a/41886794/4642212) under the linked post? This includes a full solution. – Sebastian Simon Nov 08 '22 at 18:02
  • 1
    No, you can't assign to the container at all. – Barmar Nov 08 '22 at 18:03
  • @SebastianSimon, yes, I tried to use it, but it was replacing the data attributes. – Tanker Nov 08 '22 at 18:25
  • @Tanker No, it does not. And it can’t. The top snippet filters by text nodes. Attributes can never be considered there. – Sebastian Simon Nov 08 '22 at 18:29
  • @SebastianSimon, something is messing with data attributes, didn't paid attention before, this only happen with dynamic elements, has nothing to do with what I'm looking for, at first I thought it was something I did while replacing the strings but a closer look tells me that is not. thank you. – Tanker Nov 08 '22 at 19:17

1 Answers1

1

You can use a TreeWalker or any other solusion from this answer https://stackoverflow.com/a/2579869/5089567

const walker = document.createTreeWalker(
  document.body,
  NodeFilter.SHOW_TEXT,
);


let node;
let textNodes = [];

while (node = walker.nextNode()) {
  node.nodeValue = node.nodeValue.replace(/foo/g, 'Foo')
}
<div id="content">
  <a href="foo.com/first-foo/method">The foo method</a>
  <h1>the foo.</h1>
  <p>While the foo is red</p>
  <div class="_special-foo">
    Some other foo, might not be foo.
  </div>
</div>
Konrad
  • 21,590
  • 4
  • 28
  • 64
  • 1
    funny thing I saw it and I was using Recursive Tree Traversal, but as I said on one of my comments, it was messing with the data attributes or so I thought, the good thing is that it not my doing, the bad thing is that I have to find where and when this happen. Thank you. – Tanker Nov 08 '22 at 19:34