0

I'm trying to replace the image source, but only if the image corresponds to the existing class "overview-icon--downtime". Then there's another class, "overview-icon--degraded", which I want to replace it with (or simply putting an image address, which might prove easier).

To be replaced:

<div class="page__overview">
<img class="page__overview-icon overview-icon--downtime" src="downtime_large.png">
</div>

To be replaced with:

<div class="page__overview">
<img class="page__overview-icon page__overview-icon--degraded" src="degraded_large.png">
</div>

I was thinking of this, but I'm not sure I'm heading in the right direction.

document.querySelector(".page__overview-icon overview-icon--downtime").setAttribute("img", "page__overview-icon page__overview-icon--degraded");

The image loads with the page, so I'll also need to use the AJAX at the end.

Any ideas here please? Thanks a lot in advance! :3

Shadey212
  • 11
  • 2
  • You have the same two classes in your text; "overview-icon--downtime" – Heretic Monkey Jun 13 '22 at 21:10
  • Did you mean to set the `img` attribute, or the `class` attribute? – Matthew M. Jun 13 '22 at 21:11
  • Does this answer your question? [How can I change an element's class with JavaScript?](https://stackoverflow.com/questions/195951/how-can-i-change-an-elements-class-with-javascript) – Heretic Monkey Jun 13 '22 at 21:12
  • If you want to change the `src` instead, [Programmatically change the src of an img tag](https://stackoverflow.com/q/11722400/215552) – Heretic Monkey Jun 13 '22 at 21:13
  • Sorry for the double downtime and thanks for pointing this out @HereticMonkey! Not sure what would be better solution. If I should replace only the img or class, as they overlap. – Shadey212 Jun 13 '22 at 21:21
  • "Better" sounds like an opinion, something that we don't really do on Stack Overflow. Facts and experience, sure, but how are we to determine which is better for you in your situation, in the short and long term. Too many variables. – Heretic Monkey Jun 13 '22 at 21:44

1 Answers1

-1

You are heading in the right direction.

Attributes are the things inside of the tags. In this instance, "class" and "src" are attributes of the img element.

document.querySelector will select the img element, you then need to call setAttribute('class', new class value), and setAttribute('src', new src value)

boc4life
  • 941
  • 5
  • 10
  • Setting the `class` attribute is a poor way of updating the classes applied to an element. Use modern APIs like the `classList` `DOMTokenList` API instead, as it says in the duplicate. – Heretic Monkey Jun 13 '22 at 21:15
  • You are correct, but I am attempting to give the user a better understanding of attributes as a concept. – boc4life Jun 13 '22 at 21:18