Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select an element based on an attribute containing a specific word

I am trying to target an img from a mutation like so:

var image = mutation.parentElement.querySelector('img[alt="Text"]');

The problem is, when an image has multiple alt values it's not being detected. It matches an image only if it contains "Text" only so not "Demo Text".

I want to target images like this one:

<img src="demo.jpg" alt="Apple-one Text" />

and

<img src="demo1.jpg" alt="Text" />
like image 647
oban_internet Avatar asked Sep 15 '25 21:09

oban_internet


1 Answers

You are missing a tilde in your selector:

querySelector('img[alt~="Text"]')

The tilde means it will match the element if the value provided is one of a space-separated list of values contained in that attribute. So the above will match <img alt="alt Text here" /> but not <img alt="TextA" />. If you do want to match a substring like in the second case, [attr*=val] is the way to go - https://developer.mozilla.org/en-US/docs/Learn/CSS/Introduction_to_CSS/Attribute_selectors

like image 151
Hugo Silva Avatar answered Sep 17 '25 09:09

Hugo Silva