1

I have this DOM elelement, where the part of the name of the menu [ v15rco8kc2 ] is changing for every call of the document. How Could I use a joker in the QuerySelector?

document.querySelector("#menu-v15rco8kc2 > div:nth-child(1) > button > span.Typography-module__lVnit.Typography-module__Nfgvc.Button-module__Imdmt")

1
  • @Reyno thanks, but could you help me to define the query? Do I need an attribute selector for that? And how can I formulate the syntax for the JS path in the selector. Sorry but I am novice. Commented Dec 18, 2023 at 9:03

1 Answer 1

1

Using CSS selectors, you cannot use a wildcard directly to match part of an attribute value. You can use attribute selectors to match elements based on a partial attribute value.

Demo:

  <style>
    /* Just for styling purposes */
    button {
      padding: 10px;
      background-color: #3498db;
      color: #ffffff;
      border: none;
      cursor: pointer;
    }
  </style>

<!-- Dynamic ID element -->
<div id="menu-v15rco8kc2">
  <div>
    <button>
      <span class="Typography-module__lVnit Typography-module__Nfgvc Button-module__Imdmt">
        Click me!
      </span>
    </button>
  </div>
</div>

<script>
  //get the element using the attribute selector with ^ for ID starting with "menu-"
  const dynamicElement = document.querySelector("[id^='menu-'] > div:nth-child(1) > button > span.Typography-module__lVnit.Typography-module__Nfgvc.Button-module__Imdmt");

  //add a click event listener for demonstration purposes
  dynamicElement.addEventListener('click', () => {
    alert('Element clicked!');
  });
</script>

1
  • 1
    thanks a lot ! This opens my eyes, I learnt much with your answer Commented Dec 18, 2023 at 9:07

Not the answer you're looking for? Browse other questions tagged or ask your own question.