1

This query selector doesn't work on this HTML. It works in CSS. Can anyone tell me the correct solution?

Basically, I am using an older version of the material table and want to hide the "Export as PDF" option. I know the newer version allows it in exportButton option.

<div
  class="MuiPaper-root MuiMenu-paper MuiPopover-paper MuiPaper-elevation8 MuiPaper-rounded"
  tabindex="-1"
  style="
    opacity: 1;
    transform: none;
    transition: opacity 215ms cubic-bezier(0.4, 0, 0.2, 1) 0ms,
      transform 143ms cubic-bezier(0.4, 0, 0.2, 1) 0ms;
    top: 181px;
    left: 1754px;
    transform-origin: 0px 19.5px;
  "
>
  <ul
    class="MuiList-root MuiMenu-list MuiList-padding"
    role="menu"
    tabindex="-1"
  >
    <li
      class="MuiButtonBase-root MuiListItem-root MuiMenuItem-root MuiMenuItem-gutters MuiListItem-gutters MuiListItem-button"
      tabindex="0"
      role="menuitem"
      aria-disabled="false"
    >
      Export as CSV<span class="MuiTouchRipple-root"></span>
    </li>
    <li
      class="MuiButtonBase-root MuiListItem-root MuiMenuItem-root MuiMenuItem-gutters MuiListItem-gutters MuiListItem-button"
      tabindex="-1"
      role="menuitem"
      aria-disabled="false"
    >
      Export as PDF<span class="MuiTouchRipple-root"></span>
    </li>
  </ul>
</div>
document.querySelectorAll("ul.MuiMenu-list li:contains('Export as PDF')")[0].remove();
Gaurav
  • 13
  • 3
  • Please provide more information. You have added React.js to this post's tag list but I don't see any reference that you are actually using it. It could be anything. If you're using react.js then you should replace `class` with `className` because we do it that way in React – michaelgrigoryan25 May 15 '21 at 10:53
  • Does this help you https://stackoverflow.com/questions/37098405/javascript-queryselector-find-div-by-innertext – smartdroid May 15 '21 at 11:08
  • I have picked this html from browser. I can't use css to do this operation because: 1. The css classes used here are also used everywhere else as well in dropdown. 2. I can't add id or a new class to this. – Gaurav May 15 '21 at 11:11
  • react jsx code for this is in material-table node_modules file. – Gaurav May 15 '21 at 11:13

1 Answers1

1

You need JQuery to use the :contains() Selector

$('td:contains("male")')

Also there is no CSS selector targeting on textContent. Take a look at full list of CSS3 Selectors

We need another method here :

function querySelectorIncludesText(selector, text) {
    return Array.from(document.querySelectorAll(selector)).find((el) =>
        el.textContent.includes(text)
    );
}

const find = querySelectorIncludesText("li", "Export as PDF");

console.log(find);

Now you have the correct element.

To hide an object you should NOT remove that ! You can simply change display property of element :

find.style.display = "none";
Arash Hatami
  • 5,297
  • 5
  • 39
  • 59