This post will discuss how to change the image source in JavaScript and jQuery.

Changing the image source with JavaScript and jQuery is a common task that many web developers encounter. Whether we want to create a dynamic gallery, a slideshow, a hover effect, or a simple image replacement, we need to know how to manipulate the src attribute of the <img> element.

1. Changing the image source with JavaScript

To change the image source with JavaScript, we can follow these steps:

  1. Get a reference to the image element by using its id attribute and the document.getElementById() method. The document.getElementById() method returns a reference to an element by its id attribute. The id attribute is a unique identifier for each element on the page.
  2. Assign a new URL to the src property of the image element, which represents the source URL of the image. The src property can be read or written by using the dot notation or the bracket notation.

The complete code for changing the image source with JavaScript looks like this:

JS


HTML



Edit in JSFiddle

2. Changing the image source with jQuery

To change the image source with jQuery, we need to follow these steps:

  1. Create a jQuery object that contains the image element by using its selector and the $() function. The $() function creates a jQuery object that contains one or more DOM elements using the id selector, a class selector, an element selector, or an HTML string.
  2. Change the src attribute of the image element by using the .attr() method and passing a new URL. The attr() method can set one or more attributes of the selected elements.

The complete code for changing the image source with jQuery looks like this:

JS


HTML



Edit in JSFiddle

That’s all about changing the image source in JavaScript and jQuery.