Skip to content Skip to sidebar Skip to footer

Get Background Image Url From Img Tag And Create New Img Tag With That Url

i have this
i want to take this(background) url and create new img tag with src='backgrou

Solution 1:

try this one

var img = $('#img').css('background-image');;
	
	imgURL = img.replace('url("','').replace('")','');
	img = imgURL;
	
	$('.data').html('<img src='+img+' width="100" height="100">');	
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="data"><imgsrc="#"style="background:url('o.jpg')"width="100"height="100"id="img"></div>

Solution 2:

Try below code:-

var img   = document.querySelector('img');

	// Get the background image stylevar style = img.currentStyle || window.getComputedStyle(img, false);
	var bi    = style.backgroundImage.slice(4, -1);
	
        // create a new imagevar newImage = document.createElement("IMG");

	// Replace string double quotes
	newImage.src = bi.replace(/^"|"$/g, '');;
    
        // append image inside div to current image as it next sibling 
        img.parentNode.insertBefore(newImage, img.nextSibling);

        // Remove old image
	img.parentNode.removeChild(img);
<divclass="data"><imgsrc="#"style="width:300px;height:250px;background-image: url('http://i.stack.imgur.com/5eiS4.png')"/></div>

Solution 3:

with height and width attribute http://jsfiddle.net/z2jKA/564/

remove height and width attribute http://jsfiddle.net/z2jKA/565/

I Change little Change in your coding and its working very well. you check this link jsFiddle. i was done by change some in your code. maybe its helpful for you

    $(function() {


       var img = $('#img').css('background-image');;

          imgURL = img.replace('url("','').replace('")','');
          img = imgURL;
                    alert(img);
            $("#img").attr("src",""+img+"").removeAttr('width').removeAttr('height');


});

Post a Comment for "Get Background Image Url From Img Tag And Create New Img Tag With That Url"