How to delete only part of a DOM textContent in vanilla JavaScript?

Say I have a webpage with many instances like of ( | ) scattered all over a certain HTML structure:

Text 1 ( | )
Text 2 
Text 3 ( | )
Text 4 ( | )
Text 5
...
...
... ( | )
...

How could I “brutally” delete all the ( | ) from all elements whatsoever in the webpage?
Just one command which runs on all elements and for each element deletes this specific part of the textContent.

Steps to reproduce the problem

The problem can quickly be reproduced by running the following JavaScript in Wikipedia’s own “New Pages” page.

newStyle = document.createElement("style");
newStyle.type = "text/css";
newStyle.innerHTML +=`
	  .mw-userlink,
		.mw-usertoollinks, 
		.comment,
		.mw-newpages-history,
		.mw-newpages-edit,
		.mw-newpages-length {
		  display: none;
		}
`;
document.head.appendChild(newStyle);
body.innerHTML = body.innerHTML.replacAll("( | )“,““);

There was a typo there as replacAll instead replaceAll, so I fixed it and ran the code but I got:

Uncaught SyntaxError: Invalid or unexpected token

I think that it didn’t work because any of these characters ( and | and ) appears in various parts on each paragraph in the <div> (which I have already deleted with CSS display: none;)

@m3g4p0p isn’t the problem discussed here a classical case for tree walker?

Perhaps a code which just removes each of the characters ( and | and ) in the relevant div would be good.

Credit to user Zakk from codidact.com which exampled a solution here.

document.body.innerHTML = document.body.innerHTML.replace(/x/g, '*');

Which I’ve adjusted to my particular need (a particular scope inside the body scope) this way:

document.querySelector('.new_pages').innerHTML = document.querySelector('.new_pages').innerHTML.replace(/x/g, '');

Indeed, just replacing the inner HTML of a parent element would be destructive with regard to event listeners and DOM references on the page. Using a tree walker OTOH you can replace the text node content only, keeping the element nodes and their possible references:

const walker = document.createTreeWalker(
  document.querySelector('.new_pages'),
  NodeFilter.SHOW_TEXT,
  node => node.textContent.includes('|') 
    ? NodeFilter.FILTER_ACCEPT 
    : NodeFilter.FILTER_REJECT
)

for (
  let node = walker.firstChild(); 
  node !== null;
  node = walker.nextNode()
) {
  nody.textContent = node.textContent.replace('|', '')
}

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.