3

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" />
oban_internet
  • 209
  • 1
  • 3
  • 11

1 Answers1

7

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

Hugo Silva
  • 6,748
  • 3
  • 25
  • 42
  • Given the nature of the alt attribute I think stating definitively that "You are missing a tilde in your selector" is a bit of a stretch given the semantics behind that selector (unless, of course, the asker is the one not using the alt attribute as intended, treating it like the class attribute instead or something). For example, if the alt text ends with punctuation, e.g. "Apple-one Text.", which is not unusual with alt text, then [alt~="Text"] will fail to match. – BoltClock Mar 16 '18 at 03:04
  • The author did not share his reason to be using that specific attribute, so I feel I am in no position to judge, limiting my post to objectively answer the question "How to select an element based on an attribute containing a specific word"? – Hugo Silva Mar 16 '18 at 03:10