Change href src javascript

Замена картинки И начнем мы как всегда с поиска картинки на странице при помощи метода 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. Если Вы не хотите пропустить новые материалы на сайте, то Вы можете подписаться на обновления: Подписаться на обновления Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы. Порекомендуйте эту статью друзьям: Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте): Кнопка: Она выглядит вот так: Текстовая ссылка: Она выглядит вот так: Как создать свой сайт BB-код ссылки для форумов (например, можете поставить её в подписи): Комментарии ( 0 ): Для добавления комментариев надо войти в систему. Если Вы ещё не зарегистрированы на сайте, то сначала зарегистрируйтесь. Copyright © 2010-2023 Русаков Михаил Юрьевич. Все права защищены. Источник How to dynamically change the script src? You can load JavaScript dynamically after page has loaded, but remember: once you’ve loaded it, you can’t unload JavaScript in an active page. It is stored in the browsers memory pool. You can reload a page, which will clear the active scripts, and start over. Alternatively you could override the functions that you’ve got set. With this said. Here’s how to change the script after page load with javascript:
You should avoid loading the Google Maps API more than once. If possible you should consider leaving out that script tag and instead add it through JavaScript once the dropdown (region) selection has been made. Let’s say you have a dropdown like this: Adding the script would be something like: function loadGoogleMaps() < var selectedRegion = document.getElementById("regionSelector").value; if(selectedRegion === '') < return; >var head= document.getElementsByTagName('head')[0]; var script= document.createElement('script'); script.type= 'text/javascript'; script.src= 'https://maps.googleapis.com/maps/api/js?region=' + selectedRegion; head.appendChild(script); > Источник JavaScript change img src attribute without jQuery How to change the src attribute of a HTMLImageElement in JavaScript? I need help to convert logo.attr(‘src’,’img/rm2.png’) to vanilla JavaScript. window.onresize = window.onload = function () < if (window.innerWidth >1536) < var logo = document.getElementById('rm'); logo.attr('src','img/rm2.png'); >>; 6 Answers 6 You mean you want to use pure javascript? var logo = document.getElementById('rm'); logo.src = "img/rm2.png"; So your function should look like : window.onresize = window.onload = function () < if (window.innerWidth >1536) < var logo = document.getElementById('rm'); logo.src = "img/rm2.png"; >>; window.onresize = window.onload = function () < if (window.innerWidth >1536) < var logo = document.getElementById('rm'); logo.setAttribute('src','img/rm2.png'); >>; var logo = document.getElementById('rm'); logo.setAttribute('src', 'img/rm2.png'); Since you say you want to do this in different places of the program, I would create a function like this: function ChangeImage(image_id,path) So if you want to check if the size has changes and then changes back check code bellow. window.onresize = window.onload = function () < if (window.innerWidth < 768) < var logo = document.getElementById('changeLeft'); logo.src = "MobileImage.png"; >else < var logo = document.getElementById('changeLeft'); logo.src = "DesktopImage.png"; >>; Adjust window.innerWidth to decide on your break points. Hope that helps. I think it’s just logo.src = «img/rm2.png» . Linked Related Hot Network Questions Subscribe to RSS To subscribe to this RSS feed, copy and paste this URL into your RSS reader. Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.27.43547 By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy. Источник
  • Замена картинки
  • Замена ссылки
  • Комментарии ( 0 ):
  • How to dynamically change the script src?
  • JavaScript change img src attribute without jQuery
  • 6 Answers 6
  • Linked
  • Related
  • Hot Network Questions
  • Subscribe to RSS
  • Читайте также:  Что такое update в питоне

    The attr() method will change the href of all hyperlinks to point to Google. For instance, you have a mix of link source and link target anchor tags:

    And you don’t want to add href attributes to them. Then, you can specify the selector to match the tags with an existing href attribute:

    In case you want to match an anchor with a specific existing href, then you can do the following:

    html> html> head> title>Title of the document title> script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.0/jquery.min.js"> script> head> body> a href="www.example.com">Link a> script> $("a[href]").attr("href", "https://www.w3docs.com"); script> body> html>

    Then you should update only some part of the href attribute:

    $("a[href^='http://w3docs.com']") .each(function () < this.href = this.href.replace(/^http:\/\/beta\.w3docs\.com/, "http://w3docs.com"); >);

    The first part only selects links where the href starts with http://stackoverflow.com. Then, a function is specified, which uses a regular expression to replace this part of the URL with a new one.

    The attr() Method

    The .attr() method is used to get the attribute value for the first element in the matched set. To get the value for each element, the looping construct methods, namely — .each() or .map() methods of jQuery are used.

    One of the main benefits this method suggests is that it can be called directly on a jQuery object and chained to other methods.

    Источник

    Change href src javascript

    Last updated: May 3, 2023
    Reading time · 3 min

    banner

    # How to change the href of tag using JavaScript

    To change the href of an tag using JavaScript:

    Here is the HTML for the example.

    Copied!
    DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> style> body margin: 100px; > style> head> body> a id="link" href="#">bobbyhadz.coma> button id="btn">Change hrefbutton> script src="index.js"> script> body> html>

    And here is the related JavaScript code.

    Copied!
    const btn = document.getElementById('btn'); btn.addEventListener('click', () => const link = document.getElementById('link'); link.href = 'https://bobbyhadz.com'; return false; >);

    We used the document.getElementById method to select the button and the anchor element.

    We then used the addEventListener method to add a click event listener to the button.

    Copied!
    a id="link" href="#">bobbyhadz.coma>

    When the user clicks on the button, the href attribute on the link gets set to a new value.

    Copied!
    const btn = document.getElementById('btn'); btn.addEventListener('click', () => const link = document.getElementById('link'); link.href = 'https://bobbyhadz.com'; return false; >);

    If the user clicks on the link after clicking on the button, they’d navigate to https://bobbyhadz.com .

    The code sample uses dot notation to set the value of the href attribute but you can also use the setAttribute method.

    Copied!
    const btn = document.getElementById('btn'); btn.addEventListener('click', () => const link = document.getElementById('link'); link.setAttribute('href', 'https://bobbyhadz.com'); return false; >);

    The setAttribute() method takes 2 parameters — the name of the attribute you want to set on the element and its value.

    If you also need to update the link’s text, use the innerHTML property.

    Copied!
    const btn = document.getElementById('btn'); btn.addEventListener('click', () => const link = document.getElementById('link'); link.setAttribute('href', 'https://bobbyhadz.com'); link.innerHTML = 'bobbyhadz.com - new'; return false; >);

    If you want to open the link in a new tab when it’s clicked, set the target attribute to _blank .

    Copied!
    const btn = document.getElementById('btn'); btn.addEventListener('click', () => const link = document.getElementById('link'); link.setAttribute('href', 'https://bobbyhadz.com'); // 👇️ open the link in a new tab link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener noreferrer'); >);

    The rel attribute is used for security purposes.

    # Change the href of tag using an inline event handler

    The previous example used a separate .js file, however, you can also use an inline event handler.

    Copied!
    DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> script> function changeLinkHref() console.log('href of link changed'); const link = document.getElementById('link'); link.setAttribute('href', 'https://bobbyhadz.com'); return false; > script> head> body> a id="link" href="#">bobbyhadz.coma> button onclick="changeLinkHref()">Change hrefbutton> body> html>

    The code sample sets an inline onclick event handler on the button element.

    Every time the button is clicked, the changeLinkHref function is invoked.

    Here is an example that also opens the link in a new tab and changes its text.

    Copied!
    DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> script> function changeLinkHref() console.log('href of link changed'); const link = document.getElementById('link'); link.setAttribute('href', 'https://bobbyhadz.com'); link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener noreferrer'); link.innerHTML = 'bobbyhadz.com - new'; > script> head> body> a id="link" href="#">bobbyhadz.coma> button onclick="changeLinkHref()">Change hrefbutton> --> body> html>

    # Additional Resources

    You can learn more about the related topics by checking out the following tutorials:

    • How to change the Text of an Element in JavaScript
    • Open a Link in a new tab on Button click in JavaScript
    • Detect if the Browser is in fullscreen mode in JavaScript
    • Check if a Window or a Browser Tab has Focus in JavaScript
    • Clear the Content of a Div element using JavaScript
    • ReferenceError: window is not defined in JavaScript [Solved]
    • How to set the Filename of a Blob in JavaScript
    • Disable a specific Keyboard key or all keys using JavaScript
    • How to replace plain URLs with links using JavaScript
    • How to Get the information from a meta tag using JavaScript
    • How to use ‘mailto’ in JavaScript [4 Easy Ways]

    I wrote a book in which I share everything I know about how to become a better, more efficient programmer.

    Источник

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

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

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

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

    Польза фруктов

    ананасБогатый калием, кальцием, витамином C, бета-каротином, витамином A,
    а так нерастворимой и растворимой клетчаткой.
    Ссылкана полную статью

    Замена картинки

    И начнем мы как всегда с поиска картинки на странице при помощи метода 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-код ссылки для форумов (например, можете поставить её в подписи):

    Комментарии ( 0 ):

    Для добавления комментариев надо войти в систему.
    Если Вы ещё не зарегистрированы на сайте, то сначала зарегистрируйтесь.

    Copyright © 2010-2023 Русаков Михаил Юрьевич. Все права защищены.

    Источник

    How to dynamically change the script src?

    You can load JavaScript dynamically after page has loaded, but remember: once you’ve loaded it, you can’t unload JavaScript in an active page. It is stored in the browsers memory pool. You can reload a page, which will clear the active scripts, and start over. Alternatively you could override the functions that you’ve got set.

    With this said. Here’s how to change the script after page load with javascript:

      

    You should avoid loading the Google Maps API more than once. If possible you should consider leaving out that script tag and instead add it through JavaScript once the dropdown (region) selection has been made.

    Let’s say you have a dropdown like this:

      

    Adding the script would be something like:

    function loadGoogleMaps() < var selectedRegion = document.getElementById("regionSelector").value; if(selectedRegion === '') < return; >var head= document.getElementsByTagName('head')[0]; var script= document.createElement('script'); script.type= 'text/javascript'; script.src= 'https://maps.googleapis.com/maps/api/js?region=' + selectedRegion; head.appendChild(script); > 

    Источник

    JavaScript change img src attribute without jQuery

    How to change the src attribute of a HTMLImageElement in JavaScript? I need help to convert logo.attr(‘src’,’img/rm2.png’) to vanilla JavaScript.

    window.onresize = window.onload = function () < if (window.innerWidth >1536) < var logo = document.getElementById('rm'); logo.attr('src','img/rm2.png'); >>; 

    6 Answers 6

    You mean you want to use pure javascript?

    var logo = document.getElementById('rm'); logo.src = "img/rm2.png"; 

    So your function should look like :

    window.onresize = window.onload = function () < if (window.innerWidth >1536) < var logo = document.getElementById('rm'); logo.src = "img/rm2.png"; >>; 
    window.onresize = window.onload = function () < if (window.innerWidth >1536) < var logo = document.getElementById('rm'); logo.setAttribute('src','img/rm2.png'); >>; 
    var logo = document.getElementById('rm'); logo.setAttribute('src', 'img/rm2.png'); 

    Since you say you want to do this in different places of the program, I would create a function like this:

    function ChangeImage(image_id,path)

    So if you want to check if the size has changes and then changes back check code bellow.

    window.onresize = window.onload = function () < if (window.innerWidth < 768) < var logo = document.getElementById('changeLeft'); logo.src = "MobileImage.png"; >else < var logo = document.getElementById('changeLeft'); logo.src = "DesktopImage.png"; >>; 

    Adjust window.innerWidth to decide on your break points. Hope that helps.

    I think it’s just logo.src = «img/rm2.png» .

    Linked

    Hot Network Questions

    Subscribe to RSS

    To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

    Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.27.43547

    By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

    Источник

    Оцените статью