Remove all elements with a certain textContent property

I have a MediaWiki website that presents some predefined MediaWiki Sidebar menu links that I should hide from anonymous users.

CSS command like .anonymous-user #link1, #link2 {display: none} is not an option to hide these Sidebar menu links because MediaWiki 1.32.0 has no body-class like .anonymous-user to use for hiding them just for anonymous users.

What I can do is first hiding these links for all users by JavaScript at Common.js and then selectively unhiding them for registered users at Group-autoconfirmed.js.

My problem is that the selectors formed for these links by MediaWiki are very inefficient to work with:
"#n-\.D7\.A2\.D7\.A8\.D7\.99\.D7\.9B\.D7\.AA-\.D7\.AA\.D7\.A4\.D7\.A8\.D7\.99\.D7\.98-\.D7\.96\.D7\.94"
is but one example.

Hence, I need a way to hide the links with their unique text by textContent property.
I already tried:

var elements = document.getElementsByTagName("*");
elements.forEach((element)=>{
    if (textContent == "JS1") {
        element.style.display = 'none';
    }
});

But I get:

Uncaught TypeError: elements.forEach is not a function

How to delete all elements with a certain textContent in vanilla JavaScript?

I do plan to limit the function for a specific region (like #p-navigation which uses in MediaWiki for sidebar menu).

elements is a NodeList. You cannot iterate over it using array methods.

To solve that, just turn it into an array:

const [...elements] = document.getElementsByTagName("*");
elements.forEach((element) => {
  // Do stuff with element
});

Hi there Benos,

I would also suggest that you remove the CSS from the JavaScript

CSS:-

.hide {
    display: none;
 }

JavaScript:-

<script>
(function( d ) {
   'use strict';
   var elements = d.querySelectorAll( '*' );
       elements.forEach(( element )=> {
          if ( element.textContent === 'JS1' ) {
               element.classList.add( 'hide' );
    }
});
}( document ));
</script>

coothead

Thank you both; in the end I used this code that worked fine:

const [...elements] = document.getElementsByTagName("*");
elements.forEach((element) => {
    if (element.textContent == "JS1") {
        element.style.display = 'none';
    }
});

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