Targeting two different images inside classes in the DOM

I have two images inside two classes with the same name along a document:

<a class="imagew" href="https://www.a link .com"><img src="files/theimage.png"/></a>

and

<a class="imagew" href="https://www.a link .com"><img src="files/theimage.png"/></a>

to be precise.

I need to change them at the same time by a new image (theimage2).

The first one is also inside a div, so I can do it by the following script:

document.getElementById("givendiv").getElementsByTagName("img")[0].src="files/theimage2.png";

But the second one in the document is not within any id selector. In any case, the logical way would be to get the tag img inside the “imagew” class for both of them, or maybe the tag img inside the tag “a”.

I am not sure, but I cannot do it.

Is is possible?

Thanks for any answer.

Hi there andresb,

does this help…

<!DOCTYPE HTML>
<html lang="en">
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width,height=device-height,initial-scale=1">

<title>Untitled document</title>

</head>
<body> 

<a class="imagew" href="https://www.alink.com"><img src="files/theimage.png"></a>
<a class="imagew" href="https://www.alink.com"><img src="files/theimage.png"></a>

<script>
(function( d ) {
   'use strict';
    var el = d.getElementsByClassName( 'imagew' );
    for ( var c = 0; c < el.length; c ++ ) {
          el[ c ].getElementsByTagName( 'img' )[0].src = 'files/theimage2.png';
       }
}( document ));
</script>

</body>
</html>

coothead

1 Like

Yes, it works perfectly. Thanks coothead!

Feels like a lot of effort for something that could be handled just by… changing the source code…?

1 Like

Yeah, it seems to me that if you just edited the source code, that’d be much better
Still, coothead offered a solution and it worked :slightly_smiling_face:

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.