Как изменить src картинки через js

How can I change the src attribute of an img tag using javascript? Edit at first I have a default src ...

How can I change the src attribute of an img tag using javascript?

<img src="../template/edit.png" name="edit-save" alt="Edit" />

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:

<a href="#" onclick="edit()"><img src="../template/edit.png" id="edit-save" alt="Edit" /></a>

and my JS

function edit()
{   
    var inputs = document.myform;
    for(var i = 0; i < inputs.length; i++) {
        inputs[i].disabled = false;
    }
}

I’ve tried inserting this inside the edit(), it works but need to click the image twice

var edit_save = document.getElementById("edit-save");
    edit_save.onclick = function(){
       this.src = "../template/save.png";
    }

Andy's user avatar

Andy

4,0802 gold badges24 silver badges47 bronze badges

asked Jul 30, 2012 at 13:17

Sam San's user avatar

0

Give your img tag an id, then you can

document.getElementById("imageid").src="../template/save.png";

answered Jul 30, 2012 at 13:18

Matthias's user avatar

MatthiasMatthias

12.3k13 gold badges34 silver badges55 bronze badges

2

You can use both jquery and javascript method:
if you have two images for example:

<img class="image1" src="image1.jpg" alt="image">
<img class="image2" src="image2.jpg" alt="image">

1)Jquery Method->

$(".image2").attr("src","image1.jpg");

2)Javascript Method->

var image = document.getElementsByClassName("image2");
image.src = "image1.jpg"

For this type of issue jquery is the simple one to use.

Adam Joseph Looze's user avatar

answered Feb 12, 2015 at 17:58

chandanjha's user avatar

chandanjhachandanjha

8836 silver badges5 bronze badges

2

if you use the JQuery library use this instruction:

$("#imageID").attr('src', 'srcImage.jpg');

Foreever's user avatar

Foreever

6,8018 gold badges48 silver badges55 bronze badges

answered Dec 3, 2013 at 13:52

Alessandro Pirovano's user avatar

2

its ok now

function edit()
{   
    var inputs = document.myform;
    for(var i = 0; i < inputs.length; i++) {
        inputs[i].disabled = false;
    }

    var edit_save = document.getElementById("edit-save");

       edit_save.src = "../template/save.png";                              
}

answered Jul 30, 2012 at 14:33

Sam San's user avatar

Sam SanSam San

6,4078 gold badges32 silver badges51 bronze badges

0

Give your image an id. Then you can do this in your javascript.

document.getElementById("blaah").src="blaah";

You can use this syntax to change the value of any attribute of any element.

answered Jul 18, 2014 at 23:31

Ben's user avatar

BenBen

2,15521 silver badges30 bronze badges

<img src="../template/edit.png" name="edit-save" onclick="this.src = '../template/save.png'" />

answered Jul 30, 2012 at 13:20

Donatas Olsevičius's user avatar

1

With the snippet you provided (and without making assumptions about the parents of the element) you could get a reference to the image with

document.querySelector('img[name="edit-save"]');

and change the src with

document.querySelector('img[name="edit-save"]').src = "..."

so you could achieve the desired effect with

var img = document.querySelector('img[name="edit-save"]');
img.onclick = function() {
    this.src = "..." // this is the reference to the image itself
};

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)

answered Jul 30, 2012 at 13:21

Fabrizio Calderan's user avatar

Fabrizio CalderanFabrizio Calderan

119k26 gold badges168 silver badges177 bronze badges

In this case, as you want to change the src of the first value of your element, you have no need to build up a function. You can change this right in the element:

<a href='#' onclick='this.firstChild.src="../template/save.png"')'>
  <img src="../template/edit.png" id="edit-save"/>
</a>

You have several ways to do this. You can also create a function to automatize the process:

function changeSrc(p, t) { /* where p: Parent, t: ToSource */
  p.firstChild.src = t
}

Then you can:

<a href='#' onclick='changeSrc(this, "../template/save.png");'>
  <img src="../template/edit.png" id="edit-save"/>
</a>

answered Oct 3, 2014 at 17:24

Marcelo Camargo's user avatar

Marcelo CamargoMarcelo Camargo

2,1902 gold badges21 silver badges50 bronze badges

Improve Article

Save Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    The task is to change the src attribute of the <img> element by using JQuery and JavaScript.

    • jQuery prop() Method: This method set/return properties and values of the matched elements. If this method is used to return the property value, it returns the value of the first selected element. If this method is used to set property values, it sets one or more property/value pairs for the set of selected elements.

      Syntax:

      • Return the value of a property:
        $(selector).prop(property)
      • Set the property and value:
        $(selector).prop(property, value)
      • Set property and value using a function:
        $(selector).prop(property, function(index, currentvalue))
      • Set multiple properties and values:
        $(selector).prop({property:value, property:value, ...})

      Parameters:

      • property: This parameter specifies the name of the property.
      • value: This parameter specifies the value of the property.
      • function(index, currentvalue): This parameter specifies a function that returns the property value to set.
        • index: This parameter receives the index position of element in the set.
        • currentValue: This parameter receives the current property value of selected elements.
    • jQuery on() Method: This method adds one or more event handlers for the selected elements and child elements.

      Syntax:

      $(selector).on(event, childSelector, data, function, map)

      Parameters:

      • event: This parameter is required. It specifies one or more event(s) or namespaces to attach to the selected elements. In case of multiple event values, those are separated by space. Event must be a valid.
      • childSelector: This parameter is optional. It specifies that the event handler should only be attached to the defined child elements.
      • data: This parameter is optional. It specifies additional data to pass to the function.
      • function: This parameter is required. It specifies the function to run when the event occurs.
      • map: It specifies an event map ({event:func(), event:func(), …}) having one or more event to add to the selected elements, and functions to run when the events happens.

    Example 1: This example changes the src attribute of image by using JavaScript.

    <!DOCTYPE HTML> 

    <html

        <head

            <title

                Change the src attribute

                of an img tag

            </title>     

        </head

        <body style = "text-align:center;"

            <h1 style = "color:green;"

                GeeksForGeeks 

            </h1>

            <p id = "GFG_UP" style =

                "font-size: 15px; font-weight: bold;">

            </p>

            <img id = "img" src =

            <br>

            <button onclick = "GFG_Fun()">

                click here

            </button>

            <p id = "GFG_DOWN" style

                "color:green; font-size: 20px; font-weight: bold;">

            </p>

            <script

                var up = document.getElementById('GFG_UP');

                up.innerHTML = "Click on button to change the src of image";

                var down = document.getElementById('GFG_DOWN'); 

                function GFG_Fun() {

                    document.getElementById("img").src =

                    down.innerHTML = "src attribute changed";

                }

            </script

        </body

    </html>

    Output:

    Example 2: This example changes the src attribute of image by using JQuery.

    Output:

    Improve Article

    Save Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    The task is to change the src attribute of the <img> element by using JQuery and JavaScript.

    • jQuery prop() Method: This method set/return properties and values of the matched elements. If this method is used to return the property value, it returns the value of the first selected element. If this method is used to set property values, it sets one or more property/value pairs for the set of selected elements.

      Syntax:

      • Return the value of a property:
        $(selector).prop(property)
      • Set the property and value:
        $(selector).prop(property, value)
      • Set property and value using a function:
        $(selector).prop(property, function(index, currentvalue))
      • Set multiple properties and values:
        $(selector).prop({property:value, property:value, ...})

      Parameters:

      • property: This parameter specifies the name of the property.
      • value: This parameter specifies the value of the property.
      • function(index, currentvalue): This parameter specifies a function that returns the property value to set.
        • index: This parameter receives the index position of element in the set.
        • currentValue: This parameter receives the current property value of selected elements.
    • jQuery on() Method: This method adds one or more event handlers for the selected elements and child elements.

      Syntax:

      $(selector).on(event, childSelector, data, function, map)

      Parameters:

      • event: This parameter is required. It specifies one or more event(s) or namespaces to attach to the selected elements. In case of multiple event values, those are separated by space. Event must be a valid.
      • childSelector: This parameter is optional. It specifies that the event handler should only be attached to the defined child elements.
      • data: This parameter is optional. It specifies additional data to pass to the function.
      • function: This parameter is required. It specifies the function to run when the event occurs.
      • map: It specifies an event map ({event:func(), event:func(), …}) having one or more event to add to the selected elements, and functions to run when the events happens.

    Example 1: This example changes the src attribute of image by using JavaScript.

    <!DOCTYPE HTML> 

    <html

        <head

            <title

                Change the src attribute

                of an img tag

            </title>     

        </head

        <body style = "text-align:center;"

            <h1 style = "color:green;"

                GeeksForGeeks 

            </h1>

            <p id = "GFG_UP" style =

                "font-size: 15px; font-weight: bold;">

            </p>

            <img id = "img" src =

            <br>

            <button onclick = "GFG_Fun()">

                click here

            </button>

            <p id = "GFG_DOWN" style

                "color:green; font-size: 20px; font-weight: bold;">

            </p>

            <script

                var up = document.getElementById('GFG_UP');

                up.innerHTML = "Click on button to change the src of image";

                var down = document.getElementById('GFG_DOWN'); 

                function GFG_Fun() {

                    document.getElementById("img").src =

                    down.innerHTML = "src attribute changed";

                }

            </script

        </body

    </html>

    Output:

    Example 2: This example changes the src attribute of image by using JQuery.

    Output:

    Изменение значений атрибутов у картинок и ссылок

    Изменение значений атрибутов у картинок и ссылок

    Как заменить в анонсе этой статьи одну картинку на другую и ссылку, используя знания о DOM и JavaScript?

    Изменение значений атрибутов у картинок и ссылок.


    <div class="container">
        <h1 id="heading">Польза фруктов</h1>
        <p class="text"><img src="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';
    }

    Все ссылки, ведущие на страницу с ананасами заменились на страницу с яблоками.

    Изменение значений атрибутов у картинок и ссылок.

    • Создано 02.04.2021 10:57:56


    • Михаил Русаков

    Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!

    Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
    Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.

    Если Вы не хотите пропустить новые материалы на сайте,
    то Вы можете подписаться на обновления: Подписаться на обновления

    Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы.

    Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):

    1. Кнопка:

      Она выглядит вот так: Как создать свой сайт

    2. Текстовая ссылка:

      Она выглядит вот так: Как создать свой сайт

    3. BB-код ссылки для форумов (например, можете поставить её в подписи):

    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:

    <img id="myImage" src="https://thisinterestsme.com/LOGO.png">
    
    <script>
        //Modify the src attribute of the image with the ID "myImage"
        document.getElementById("myImage").src = 'img/new-image.jpg';
    </script>

    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:

    //Get our img element by using document.getElementById
    var img = document.getElementById("myImage");
    
    //Set the src property of our element to the new image URL
    img.src = 'img/new-image.jpg';

    In this case, we have broken the process up into two steps:

    1. 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.
    2. 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:

    //Change the img property using jQuery's attr method
    $("#myImage").attr("src", 'img/new-image.jpg');

    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:

    //Change the img property and use load() to figure out when
    //the new image has been loaded
    $("#myImage").attr("src", 'img/new-image.jpg').load(function(){
        alert('New image loaded!');
    });

    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.

    Понравилась статья? Поделить с друзьями:
  • Как изменить sprite unity
  • Как изменить spfile
  • Как изменить spf запись для почтового сервера
  • Как изменить spd оперативной памяти
  • Как изменить spawn rate minecraft