Search code examples
javascriptdomjquery-selectors

How can I select a DOM element, which name is changing


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")


Solution

  • 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>