The src stands for source. In fact, without the src attribute, we will not be able to specify what image we want to be displayed. We can also indicate the size of an image by using height and width attributes. However, in the modern world, most developers prefer CSS to specify the size of the image.
In the following example, we have multiple images in the images directory. We also have 4 button elements and one image element. Upon click of each button, we will pick one image from the images directory and set it as a source of the image element. Please have a look over the code example and the steps given below.
HTML & CSS
We have 3 elements in the HTML file (div, img, and button). The div element is just a wrapper for the button elements.
By default, we have 1.jpg as a source for the image element.
We have done some basic styling using CSS and added the link to our style.css stylesheet inside the head element.
We have selected all the button elements and the img element using the document.querySelector() method and stored them in the btn1, btn2, btn3, btn4, and img variables respectively.
We have attached a click event listener to all the button elements.
In the click event handler function of each button element, we are using the src property of the img element to change the image with one of the images present in the images directory.
In the case of the 4th click event handler function, we are not picking an image from the images directory using a relative URL rather we are using an absolute URL. The browser will load the image from that absolute URL.