Как поменять фото через код элемента
Перейти к содержимому

Как поменять фото через код элемента

  • автор:

Change HTML image src using JavaScript code

You can change an HTML image src attribute programatically by using JavaScript. First, you need to grab the HTML element by using JavaScript element selector methods like getElementById() or querySelector() and assign the element to a variable.

After you have the element, you can assign a new string value to its src property as follows:

When you have the image in another folder, than you need to add the image path to the src attribute as well. The code below shows how to change the src attribute to an image inside the assets/ folder:

Finally, if you need to run some JavaScript code after a new image has been loaded to the element, you can add an onload event loader to your img element before changing the src attribute as follows:

Using the above code, an alert will be triggered when the new image from the src attribute has been loaded to the HTML page.

Take your skills to the next level ⚡️

I’m sending out an occasional email with the latest tutorials on programming, web development, and statistics. Drop your email in the box below and I’ll send new stuff straight into your inbox!

About

Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
Learn statistics, JavaScript and other programming languages using clear examples written for people.

How to Change Img Src using JavaScript

The cool thing about JavaScript is that you can use it to programmatically alter the DOM.

This includes the ability to change an image’s src attribute to a new value, allowing you to change the image being loaded.

In this post, we will learn how we can use JavaScript to change the src attribute of an image.

Chaning an Image’s src Attribute

Let’s assume this is our DOM:

The first step is to query the DOM for this image. We can do this by using the querySelector() method.

Now that we have our element, we can change the src attribute of the image.

This turns the DOM into this:

On Load

Sometimes, you want to run some code after the image has loaded. Thankfully, this is easily accomplished by simply adding an event listener to the image.

Now, when the image has loaded, the function will execute, printing to the console. You can do whatever you want, including changing the src attribute of the image to another image.

Conclusion

In this post, we’ve seen how we can use JavaScript to change the src attribute of an image.

If you want, you can also run some code after the image has loaded.

Hopefully, you’ve enjoyed this post, thanks for reading!

If you want to learn about web development, founding a start-up, bootstrapping a SaaS, and more, follow me on Twitter! You can also join the conversation over at our official Discord!

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *