1

i want to change the src of the image tag given below to images/hero-desktop.jpg

<img src="images/hero-mobile.jpg" alt="" class="image">

using javascript i tried

value=800;

if(screen.width > value){
    document.getElementsByClassName('image').src="images/hero-desktop.jpg";
}

but it doesnt work. the js file is linked and working(checked by console log).

can anyone help me out????

  • Does this answer your question? [What do querySelectorAll and getElementsBy\* methods return?](https://stackoverflow.com/questions/10693845/what-do-queryselectorall-and-getelementsby-methods-return) – A1rPun May 29 '21 at 15:22

3 Answers3

1

It is a silly mistake .

document.getElementsByClassName('image') is returning a array .

why

Now you are thinking while document.getElementsById is working fine without [0] mean returning specific item but document.getElementsByClassName returning an array .

Because id is unique for each element while multiple element can have same class (for optimize CSS performance ) so always its gonna return a array

In your case u want to access the first element so use

document.getElementsByClassName('image')[0]

Working Snippet

let value=800;

if(screen.width > value){
    document.getElementsByClassName('image')[0].src="https://picsum.photos/500";
}
console.log(screen.width);
<img src="https://picsum.photos/200" alt="" class="image">
S B RAKESH RATH
  • 443
  • 3
  • 10
0

You can use the picture/srcset/sizes to achieve that.

From MDN docs:

<img srcset="elva-fairy-480w.jpg 480w,
             elva-fairy-800w.jpg 800w"
     sizes="(max-width: 600px) 480px,
            800px"
     src="elva-fairy-800w.jpg"
     alt="Elva dressed as a fairy">
Shravan Dhar
  • 1,455
  • 10
  • 18
0

You can use the querySelector for that. Just like @JagadishLenka said, getElementsByClassName returns a HTMLCollection.

const max_width = 800;

if (screen.width > max_width)
    document.querySelector('.image').src = "images/hero-desktop.jpg";
A1rPun
  • 16,287
  • 7
  • 57
  • 90