search
HomeWeb Front-endJS TutorialHow to change the src attribute of an img element in JavaScript/jQuery?

Using JavaScript and jQuery, there are different ways to change the image path given in the src attribute of the How to change the src attribute of an img element in JavaScript/jQuery? element in an HTML document.

How to use JavaScript to change the src attribute of the img element−

  • Use the src attribute in JavaScript.

How to use jQuery to change the src attribute of the img element−

  • Use attr() method

  • Use prop() method

Let us discuss the above listed methods of changing the src of the img element in detail one by one.

Using the src attribute in JavaScript

JavaScript allows us to use the src attribute to get the value that has been assigned to it, and also to update or change the value of the same attribute. This is a very common way to change the value of the src attribute of an img element.

Syntax

The following syntax will explain to you how to use the src attribute in JavaScript to change the value of the src attribute of the img element -

Selected_image_element.src = " new value ";

Let us understand the practical implementation of this approach through a code example.

algorithm

  • Step 1 − In the first step, we will add an img element with a src attribute associated with it, whose value we will change later using the src property in JavaScript.

  • Step 2 - In this step, we will add a button element with an onclick event and call a function to change the src of the image when the user clicks the button.

  • Step 3 - In the next step, we will define a JavaScript function in which we will get the img element using its ID and then change the src attribute using Switch between two images.

  • Step 4 − In the last step, we will assign the function to the onclick event defined in the last step to see the changes on user screen.

The Chinese translation of

Example

is:

Example

The following example will explain to you how to actually use the src attribute in JavaScript to change the src attribute of an img.

<html>
<body>
   <h2 id="Change-the-src-attribute-of-an-img-element">Change the src attribute of an img element</h2>
   <p id = "upper">The image shown below will be changed once you click the button.</p>
   <img  src="/static/imghwm/default1.png"  data-src="https://img.php.cn/"  class="lazy"  src =  "https://img.php.cn/" id = "image" alt="How to change the src attribute of an img element in JavaScript/jQuery?" > <br> <br>
   <button id = "btn" onclick = "changeSrc()">Click to change the Image</button>
   <p id = "result"> </p>
   <script>
      var result = document.getElementById("result");
      var upper = document.getElementById("upper");
      function changeSrc() {
         var img = document.getElementById('image');
         if (img.src == "https://img.php.cn/") {
            img.src = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSoLnvRnTNP2rojd7e9b_Ilw5zZkSlPotSPIA&usqp=CAU";
            result.innerHTML += " The src of above img is changed from <b> Link 1 </b> to " + " <b> Link 2 </b> <br>";
         }
         else {
            img.src = "https://img.php.cn/";
            result.innerHTML += " The src of above img is changed from <b> Link 2 </b> to " + " <b> Link 1 </b> <br>";
         }
         upper.innerHTML = " The image shown previously is replaced by some other image as <b> src attribute of img is changed. </b> <br> ";
      }
   </script>
</body>
</html>

In this example, we use the src attribute in JavaScript to change the src attribute of the img element in the HTML document. Here, we switch between two images every time the button is clicked.

Using the attr() method in jQuery

We can also use the attr() method in JavaScript to change the src attribute.

attr() method - The attr() method accepts two parameters. The first parameter is the name of the attribute to be changed, expressed in string form, and the other parameter is the new value to be assigned to the attribute. value.

Syntax

The following syntax will explain to you how the attr() method with parameters is implemented−

attr(" attribute_name ", " new_value ");

Let us understand the implementation of this method in detail through a code example.

algorithm

  • Step One - In the

    of the <script> element of the document we will add the jQuery link <src> </script>
  • Step 2 - In this step, we will use an img element with a src attribute, and later use jQuery's attr() method to modify it

  • Step 3 - In step 3 we will add a button element which will later be given an onclick event and a function using jQuery

  • Step 4 − In the next step, we will use jQuery's "$" syntax to get each element and perform tasks on each element.

  • Step 5 − In the last step, we will use jQuery’s on() method to assign an onclick event to the button, so that when the user clicks the button, It calls the function given in it and the changes are visible to the user.

  • The Chinese translation of
Example

is:

Example

The following example will illustrate using the attr() method in jQuery to change the src attribute of the img element:

<html>
<head>
   <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
</head>
<body>
   <h2 id="Change-the-src-attribute-of-an-img-element-using-jQuery">Change the src attribute of an img element using jQuery</h2>
   <p id = "upper">The image shown below will be changed once you click the button.</p>
   <img  src="/static/imghwm/default1.png"  data-src="https://img.php.cn/"  class="lazy"  src = "https://img.php.cn/" id = "image" alt="How to change the src attribute of an img element in JavaScript/jQuery?" > <br> <br>
   <button id = "btn">Click to change the Image</button>
   <p id = "result"> </p>
   <script>
      $("#btn").on('click', function (e) {
         $('#image').attr("src", "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSoLnvRnTNP2rojd7e9b_Ilw5zZkSlPotSPIA&usqp=CAU");
         $("#result").html(" The src of above img is changed from <b> Link 1 </b> to " + " <b> Link 2 </b> <br>");
         $("#upper").html(" The image shown previously is replaced by some other image as <b> the src attribute of img is changed. </b> <br> ");
      });
   </script>
</body>
</html>

Use the prop() method in jQuery

Similar to the attr() method, jQuery also provides the prop() method to change the value of any attribute to a new value.

prop() method − The prop() method can be used as we used the attr() method in previous example. It takes property name and the new value to be assigned as parameters.

We can use the prop() method to set values ​​to single properties and multiple properties.

Syntax

Following syntax will show you how you can use the prop() method for different purposes −

Change the value of a specific attribute

prop(" attribute_name ", " new_value ");

Change the values ​​of multiple attributes

prop({ attribute_name: new_value, attribute_name: new_value });

In the second syntax, we provide multiple properties with their new values ​​at the same time.

Let us learn more about the usage of prop() method through code examples.

algorithm

The algorithm of this example is almost similar to the algorithm of the previous example. You just need to replace the attr() method in the previous algorithm with the prop() method and the job will be done.

The Chinese translation of

Example

is:

Example

The following example will explain to you how the prop() method changes the value of the src attribute of the img element in an HTML document -

<html>
<head>
   <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
</head>
<body>
   <h2 id="Changing-the-src-attribute-of-an-img-element-using-jQuery">Changing the src attribute of an img element using jQuery</h2>
   <p id = "upper">The image shown below will be changed once you click the button.</p>
   <img  src="/static/imghwm/default1.png"  data-src="https://img.php.cn/"  class="lazy" id = "image" alt="How to change the src attribute of an img element in JavaScript/jQuery?" > <br> <br>
   <button id = "btn">Click to change the Image</button>
   <p id = "result"> </p>
   <script>
      $("#btn").on('click', function (e) {
         $('#image').prop("src", "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSoLnvRnTNP2rojd7e9b_Ilw5zZkSlPotSPIA&usqp=CAU");
         $("#result").html(" The src of above img is changed from <b> Link 1 </b> to " + " <b> Link 2 </b> <br>");
         $("#upper").html(" The image shown previously is replaced by some other image as <b> src attribute of img is changed. </b> <br> ");
      });
   </script>
</body>
</html>

In the above example, we used the prop() method in jQuery to change the src attribute of the img element in the HTML document.

In this article, we have discussed about the three different methods of changing the value of the src attribute of an img element using the JavaScript as well as jQuery. We have understand all the methods in details by practically implementing them inside the code examples, which helps to build the practical knowledge of the concepts.

The above is the detailed content of How to change the src attribute of an img element in JavaScript/jQuery?. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:tutorialspoint. If there is any infringement, please contact admin@php.cn delete
Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor