我有这个DOM elElement,其中菜单[v15rco8kc2]的名称部分在每次调用文档时都会发生变化.我怎么能在QuerySelector中使用小丑呢?

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

推荐答案

使用css Select 器时,不能直接使用wildcard来匹配attribute值的一部分. 可以使用attribute selectors来匹配基于部分attribute值的元素.

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>

Javascript相关问答推荐

如何在JavaScript中在文本内容中添加新行

我可以使用CSS有效地实现最大宽度=100%和最大高度=100%,而无需父母有明确的/固定的宽度和高度,替代方法吗?

Redux查询多个数据库Api reducerPath&

VUE 3捕获错误并呈现另一个组件

不能将空字符串传递给cy.containes()

rxjs插入延迟数据

JQuery Click事件不适用于动态创建的按钮

在浏览器中触发插入事件时检索编码值的能力

使用js构造一个html<;ath&>元素并不能使其正确呈现

如何在DYGRAPS中更改鼠标事件和键盘输入

获取';无法解决导入和导入";slick-carousel/slick/slick-theme.css";';错误

MongoDB受困于太多的数据

删除加载页面时不存在的元素(JavaScript)

FindByIdAndUpdate在嵌套对象中创建_id

在没有任何悬停或其他触发的情况下连续交换图像

由于http.get,*ngIf的延迟很大

MAT-TREE更多文本边框对齐问题

将匿名函数附加到链接的onClick属性

浮动标签效果移除时,所需的也被移除

带有JS模块模式的Rails的Importmap错误:";Net::ERR_ABORTED 404(未找到)&Quot;