如何 select 基于包含特定词的属性的元素
How to select an element based on an attribute containing a specific word
我正在尝试从像这样的突变中定位 img:
var image = mutation.parentElement.querySelector('img[alt="Text"]');
问题是,当图像具有多个 alt 值时,它不会被检测到。它仅在图像包含 "Text" 时匹配图像,而不是 "Demo Text".
我想定位像这样的图片:
<img src="demo.jpg" alt="Apple-one Text" />
和
<img src="demo1.jpg" alt="Text" />
您的选择器中缺少波浪号:
querySelector('img[alt~="Text"]')
波浪号表示如果提供的值是该属性中包含的 space-separated 值列表之一,它将匹配该元素。所以以上将匹配 <img alt="alt Text here" />
但不匹配 <img alt="TextA" />
。如果您确实想像第二种情况那样匹配子字符串,[attr*=val]
是可行的方法 - https://developer.mozilla.org/en-US/docs/Learn/CSS/Introduction_to_CSS/Attribute_selectors
我正在尝试从像这样的突变中定位 img:
var image = mutation.parentElement.querySelector('img[alt="Text"]');
问题是,当图像具有多个 alt 值时,它不会被检测到。它仅在图像包含 "Text" 时匹配图像,而不是 "Demo Text".
我想定位像这样的图片:
<img src="demo.jpg" alt="Apple-one Text" />
和
<img src="demo1.jpg" alt="Text" />
您的选择器中缺少波浪号:
querySelector('img[alt~="Text"]')
波浪号表示如果提供的值是该属性中包含的 space-separated 值列表之一,它将匹配该元素。所以以上将匹配 <img alt="alt Text here" />
但不匹配 <img alt="TextA" />
。如果您确实想像第二种情况那样匹配子字符串,[attr*=val]
是可行的方法 - https://developer.mozilla.org/en-US/docs/Learn/CSS/Introduction_to_CSS/Attribute_selectors