0

i am getting image url in style tag by default i want to replace src="#" with the image url in the style tag using js i dont know how to do this

 <img src="#" style="background:url('https://example.com/1.jpg') no-repeat center center;-webkit-background-size:cover;background-size:cover;width:660px;height:330px;"class="demo-class">

final code is like

 <img src="https://example.com/1.jpg" style="background:url('https://example.com/1.jpg') no-repeat center center;-webkit-background-size:cover;background-size:cover;width:660px;height:330px;"class="demo-class">
Maulik Lathiya
  • 153
  • 3
  • 14

4 Answers4

2

You want to parse the current style of the element, get the URL out and update the src attribute.

To remove style, use:

img.removeAttribute('style');

var img = document.querySelector('img'),
    // parse image URL and strip away url('')
    imgURL = img.style.backgroundImage.replace('url("','').replace('")','');
img.src = imgURL;

// remove style attribute afterwards.
img.removeAttribute('style');
<img src="#" style="background:url('https://unsplash.it/400') no-repeat center center;-webkit-background-size:cover;background-size:cover;width:660px;height:330px;"class="demo-class">
Adam Azad
  • 11,171
  • 5
  • 29
  • 70
  • how do i remove style from ? – Maulik Lathiya Jun 16 '17 at 08:59
  • i dont know why but this is not working on the site so i am doing this the image is inside a div "single-post-thumb" so i want to take the image url in a variable and add a new image tag in that div with that image url and delete old image tag how do i take that image url in a var and delete the old img tag ? $('.single-post-thumb').prepend('') – Maulik Lathiya Jun 16 '17 at 09:36
0

You can select img tags by class name like below and change src property:

var imgs = document.getElementsByClassName('demo-class')
var img = imgs[0];
img.src = img.style.backgroundImage.replace(/url\((.*)\)/,'$1');
img.style.backgroundImage = null
 <img src="#" style="background:url('https://example.com/1.jpg') no-repeat center center;-webkit-background-size:cover;background-size:cover;width:660px;height:330px;" class="demo-class">
Mohammad Hamedani
  • 3,304
  • 3
  • 10
  • 22
0
    //using javascript
    document.getElementById('imgTagId').src = 'https://example.com/1.jpg';

    //using jquery
    $('#imgTagId').attr('src','https://example.com/1.jpg');


//using style background-image
var imageUrl = $('#imgTagId').css("background-image");
document.getElementById('imgTagId').src = imageUrl.split(/"/)[1];
ajay92x
  • 83
  • 11
-1

Give your image an tag an id then you can do something like this: document.getElementById("imageid").src="../template/save.png"

for more information there is a similar question Programmatically change the src of an img tag

Aleksa
  • 1