Изменение значений атрибутов у картинок и ссылок
Как заменить в анонсе этой статьи одну картинку на другую и ссылку, используя знания о DOM и JavaScript?
<div >
<h1 >Польза фруктов</h1>
<p ><img src=»https://myrusakov.ru/pineapple.png» alt=»ананас»> Богатый калием, кальцием, витамином C, бета-каротином, витамином A,
а так нерастворимой и растворимой клетчаткой.<br><a href=»https://site.ru/ananas»><b>Ссылка</b></a>на полную статью
</p>
</div>
Замена картинки
И начнем мы как всегда с поиска картинки на странице при помощи метода getElementsByTagName. Слово Elements в названии метода указывает на то, что элементов (тегов) может быть несколько. Объявляем переменную image и присваиваем ей найденный тег img.
// Поиск картинки по тегу img
let image = document.getElementsByTagName('img');
// Вывод значения переменной в консоль для самопроверки для новичков
console.log(image);
Так и есть, метод getElementsByTagName действительно вернул HTML коллекцию.
Поскольку данный метод возвращает несколько элементов из коллекции HTMLCollection, то мы должны перебрать их в цикле. Зададим нулевое значение счетчику и будем перебирать элементы, каждый раз прибавляя единицу, до достижения длины коллекции. Что мы пропишем внутри цикла? Свойство innerHTML здесь не подходит, поскольку у тега img не может быть вложенного элемента. В случае с картинками, меняется название картинки pineapple, прописанного в значении атрибута src, на другое название pineapple_best.png. Изменим атрибут src у тега img (его мы поместили в переменную image), сначала отобрав нужный элемент при помощи квадратных скобок. Затем ставим точку и после точки пишем атрибут src и присваиваем ему новое значение — название файла картинки.
let image = document.getElementsByTagName('img');
for (let i = 0; i < image.length; i++) <
image[i].src = 'pineapple_best.png';
>
В результате изображение одного ананаса поменялось на изображение другого ананаса.
Замена ссылки
Как найти и заменить текущую ссылку в статье на новую ссылку при помощи JavaScript, учитывая что таких ссылок может быть несколько? Отберем все ссылки, ведущие на статьи про ананасы и заменим их на статьи про яблоки при помощи CSS селектора.
Построим уникальный CSS селектор, где упоминаются только ананасы. Сначала отберем теги ссылок a, затем в квадратных скобках напишем атрибут href, (*) и слово ananas. Такой CSS селектор выберет все ссылки, в адресах которых встречается слово «ananas». Мы сделали селектор для нестандартного поиска в документе и окрасили его в зеленый цвет.
a[href*=»ananas»] <
color: greenyellow;
>
Метод querySelectorAll ищет элементы по любым селекторам. Передадим в аргументы метода наш селектор, экранируя кавычки обратными косыми. Затем пройдемся по всем ссылкам в цикле и укажем в значении атрибута href, новую ссылку на статью про яблоки.
let links = document.querySelectorAll('[href*=\»ananas»\]');
console.log(links); //NodeList [a]
for (let i = 0; i < links.length; i++) <
links[i].href = 'https://site.ru/apple';
>
Все ссылки, ведущие на страницу с ананасами заменились на страницу с яблоками.
Change the “src” attribute of an image using JavaScript.
This is a tutorial on how to change the “src” attribute of an image using JavaScript.
The src attribute specifies the URL of an image. Therefore, by setting a new src, we can dynamically change the image in question.
In this post, I will show you how to accomplish this using both regular JavaScript and jQuery.
Changing the src attribute using regular JavaScript.
If you’re not already using jQuery, then there is no sense in including the library just to manipulate the src attribute. Instead, you can just use vanilla JavaScript, which tends to be faster.
Take a look at the example below:
If you run the snippet above, you will see that the src attribute of our image element is replaced by our JavaScript code.
A more verbose example for those of you who want to understand what is going on here:
In this case, we have broken the process up into two steps:
- We retrieved the img element from our HTML DOM by using the method document.getElementById(). We passed “myImage” in as the parameter because that is the ID of our image.
- After retrieving the img, we were able to modify its src attribute and assign a new URL.
This will force the browser to load our new image.
Changing the img src using jQuery.
If you’re already using the jQuery library and you would like to keep your code consistent, you can use the following method:
In the code above, we referenced the image by its ID and then used jQuery’s attr() method to set a new value for its src attribute.
Determining when the new image is loaded.
If you need to do something after the new image has loaded, then you can attach jQuery’s load() method to our example above:
Once jQuery has changed the src property and the image from the new URL has been loaded in the browser, the code inside the load() method will execute. However, this load block will not execute if the image in question doesn’t exist.
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.
Learn JavaScript for Beginners
Get the JS Basics Handbook, understand how JavaScript works and be a confident software developer.
A practical and fun way to learn JavaScript and build an application using Node.js.
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.
Programmatically change the src of an img tag
How can I change the src attribute of an img tag using javascript?
at first I have a default src which is "../template/edit.png" and I wanted to change it with "../template/save.png" onclick.
UPDATED: here’s my html onclick:
I’ve tried inserting this inside the edit(), it works but need to click the image twice
9 Answers 9
Give your img tag an id, then you can
You can use both jquery and javascript method: if you have two images for example:
For this type of issue jquery is the simple one to use.
if you use the JQuery library use this instruction:
Give your image an id. Then you can do this in your javascript.
You can use this syntax to change the value of any attribute of any element.
With the snippet you provided (and without making assumptions about the parents of the element) you could get a reference to the image with
and change the src with
so you could achieve the desired effect with
otherwise, as other suggested, if you’re in control of the code, it’s better to assign an id to the image a get a reference with getElementById (since it’s the fastest method to retrieve an element)
Как изменить src через js
Change the “src” attribute of an image using JavaScript.
This is a tutorial on how to change the “src” attribute of an image using JavaScript.
The src attribute specifies the URL of an image. Therefore, by setting a new src, we can dynamically change the image in question.
In this post, I will show you how to accomplish this using both regular JavaScript and jQuery.
Changing the src attribute using regular JavaScript.
If you’re not already using jQuery, then there is no sense in including the library just to manipulate the src attribute. Instead, you can just use vanilla JavaScript, which tends to be faster.
Take a look at the example below:
If you run the snippet above, you will see that the src attribute of our image element is replaced by our JavaScript code.
A more verbose example for those of you who want to understand what is going on here:
In this case, we have broken the process up into two steps:
- We retrieved the img element from our HTML DOM by using the method document.getElementById(). We passed “myImage” in as the parameter because that is the ID of our image.
- After retrieving the img, we were able to modify its src attribute and assign a new URL.
This will force the browser to load our new image.
Changing the img src using jQuery.
If you’re already using the jQuery library and you would like to keep your code consistent, you can use the following method:
In the code above, we referenced the image by its ID and then used jQuery’s attr() method to set a new value for its src attribute.
Determining when the new image is loaded.
If you need to do something after the new image has loaded, then you can attach jQuery’s load() method to our example above:
Once jQuery has changed the src property and the image from the new URL has been loaded in the browser, the code inside the load() method will execute. However, this load block will not execute if the image in question doesn’t exist.
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!
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.
Level up your programming skills
I'm sending out an occasional email with the latest programming tutorials. Drop your email in the box below and I'll send new stuff straight into your inbox!
About
Sebhastian is a site that makes learning programming easy with its step-by-step, beginner-friendly tutorials.
Learn JavaScript and other programming languages with clear examples.
Search
Type the keyword below and hit enter
Click to see all tutorials tagged with:
How to Change Image Source JavaScript
JavaScript can integrate with HTML to fulfill the demands of users. By integration, users can employ a feature to change the image source. For instance, the src property is utilized to specify the image source. The sources may include a local file system as well as the image URL. This guide serves to change the image source file by utilizing the src property. All the latest browsers support the src property for locating the source image.
This post serves the following learning outcomes:
How to Change the Image Source in JavaScript
JavaScript is essential for dynamically changing the display of the image. For instance, the img HTML element provides the src property to modify the source of the image. The source of the image may be a local system or any URL image.
The syntax to apply the src property using JavaScript is provided below:
Syntax
Parameter
The description of the parameters is as follows:
- myImageId: specifies the image id.
- src: refers to the source of the image.
Example 1: Change Image Source of the Local Image
An example is adapted to change the source of an image through the local file in JavaScript. The example comprises HTML and JavaScript code files.
HTML Code
In this code, the src attribute is utilized to fetch the image “computer.jpg“. After that, a “Change Image Button” is added to the HTML file that triggers the changeScr() method. The changeScr() method is written in a JavaScript file.
JavaScript Code
In this code, the changeSrc() method fetches the element using its id “imgid” and sets the value of the “src” attribute of that element.
Output
The output shows that after pressing the “Change Image Button” the source file of the image is changed, and the new image is displayed.
Example 2: Change Image Source of a Web-Based Image
Another example is employed for changing the image source through the URL in JavaScript. The complete code is divided into HTML and JavaScript files.
HTML Code
The description of the code is as below:
- Firstly, the width and height of the image are assigned to the image within <img> tags.
- After that, the URL of an image is provided by the src property to display the image in the browser window.
JavaScript Code
In this code, the changeScr() method is used to trigger an event when the user clicks on the button to change the source of the image.
Output
The output illustrates that when a user clicks on the “Change Image”, the new image is replaced with the existing one.
Conclusion
JavaScript provides a src attribute to change the image source by specifying the path of the file. For instance, the getElementId() method is utilized to extract the HTML element through id, and then the src property will change the source image. After extraction, the new source image file is assigned. Here, you have learned to change the image source in JavaScript. For this, we have demonstrated a set of examples in various scenarios.
About the author
Syed Minhal Abbas
I hold a master’s degree in computer science and work as an academic researcher. I am eager to read about new technologies and share them with the rest of the world.
Изменение значений атрибутов у картинок и ссылок
Как заменить в анонсе этой статьи одну картинку на другую и ссылку, используя знания о DOM и JavaScript?
<div >
<h1 >Польза фруктов</h1>
<p ><img src=»https://myrusakov.ru/pineapple.png» alt=»ананас»> Богатый калием, кальцием, витамином C, бета-каротином, витамином A,
а так нерастворимой и растворимой клетчаткой.<br><a href=»https://site.ru/ananas»><b>Ссылка</b></a>на полную статью
</p>
</div>
Замена картинки
И начнем мы как всегда с поиска картинки на странице при помощи метода getElementsByTagName. Слово Elements в названии метода указывает на то, что элементов (тегов) может быть несколько. Объявляем переменную image и присваиваем ей найденный тег img.
// Поиск картинки по тегу img
let image = document.getElementsByTagName('img');
// Вывод значения переменной в консоль для самопроверки для новичков
console.log(image);
Так и есть, метод getElementsByTagName действительно вернул HTML коллекцию.
Поскольку данный метод возвращает несколько элементов из коллекции HTMLCollection, то мы должны перебрать их в цикле. Зададим нулевое значение счетчику и будем перебирать элементы, каждый раз прибавляя единицу, до достижения длины коллекции. Что мы пропишем внутри цикла? Свойство innerHTML здесь не подходит, поскольку у тега img не может быть вложенного элемента. В случае с картинками, меняется название картинки pineapple, прописанного в значении атрибута src, на другое название pineapple_best.png. Изменим атрибут src у тега img (его мы поместили в переменную image), сначала отобрав нужный элемент при помощи квадратных скобок. Затем ставим точку и после точки пишем атрибут src и присваиваем ему новое значение — название файла картинки.
let image = document.getElementsByTagName('img');
for (let i = 0; i < image.length; i++) <
image[i].src = 'pineapple_best.png';
>
В результате изображение одного ананаса поменялось на изображение другого ананаса.
Замена ссылки
Как найти и заменить текущую ссылку в статье на новую ссылку при помощи JavaScript, учитывая что таких ссылок может быть несколько? Отберем все ссылки, ведущие на статьи про ананасы и заменим их на статьи про яблоки при помощи CSS селектора.
Построим уникальный CSS селектор, где упоминаются только ананасы. Сначала отберем теги ссылок a, затем в квадратных скобках напишем атрибут href, (*) и слово ananas. Такой CSS селектор выберет все ссылки, в адресах которых встречается слово «ananas». Мы сделали селектор для нестандартного поиска в документе и окрасили его в зеленый цвет.
a[href*=»ananas»] <
color: greenyellow;
>
Метод querySelectorAll ищет элементы по любым селекторам. Передадим в аргументы метода наш селектор, экранируя кавычки обратными косыми. Затем пройдемся по всем ссылкам в цикле и укажем в значении атрибута href, новую ссылку на статью про яблоки.
let links = document.querySelectorAll('[href*=\»ananas»\]');
console.log(links); //NodeList [a]
for (let i = 0; i < links.length; i++) <
links[i].href = 'https://site.ru/apple';
>
Все ссылки, ведущие на страницу с ананасами заменились на страницу с яблоками.
Change the “src” attribute of an image using JavaScript.
This is a tutorial on how to change the “src” attribute of an image using JavaScript.
The src attribute specifies the URL of an image. Therefore, by setting a new src, we can dynamically change the image in question.
In this post, I will show you how to accomplish this using both regular JavaScript and jQuery.
Changing the src attribute using regular JavaScript.
If you’re not already using jQuery, then there is no sense in including the library just to manipulate the src attribute. Instead, you can just use vanilla JavaScript, which tends to be faster.
Take a look at the example below:
If you run the snippet above, you will see that the src attribute of our image element is replaced by our JavaScript code.
A more verbose example for those of you who want to understand what is going on here:
In this case, we have broken the process up into two steps:
- We retrieved the img element from our HTML DOM by using the method document.getElementById(). We passed “myImage” in as the parameter because that is the ID of our image.
- After retrieving the img, we were able to modify its src attribute and assign a new URL.
This will force the browser to load our new image.
Changing the img src using jQuery.
If you’re already using the jQuery library and you would like to keep your code consistent, you can use the following method:
In the code above, we referenced the image by its ID and then used jQuery’s attr() method to set a new value for its src attribute.
Determining when the new image is loaded.
If you need to do something after the new image has loaded, then you can attach jQuery’s load() method to our example above:
Once jQuery has changed the src property and the image from the new URL has been loaded in the browser, the code inside the load() method will execute. However, this load block will not execute if the image in question doesn’t exist.
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!