我有这个DOM elElement,其中菜单[v15rco8kc2]的名称部分在每次调用文档时都会发生变化.我怎么能在QuerySelector中使用小丑呢?
document.querySelector("#menu-v15rco8kc2 > div:nth-child(1) > button > span.Typography-module__lVnit.Typography-module__Nfgvc.Button-module__Imdmt")
我有这个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>