user3014202
user3014202

Reputation: 99

Append image using javascript attr src function

I want to get the image src from a div with id post and want to append it inside a div with id show-image

Also I want to wrap the javascript in a function so that I can implement it in webpage

so far i have created this

var theDiv = document.getElementById("show-image");
var tubeimg = document.getElementById('post-img').getAttribute('src');
theDiv.innerHTML += "<img src=" +tubeimg+ " />"; 

for the Html coding

<div id='show-image'>
</div>
<div id='post'>
<div class='inner'>
<img id='post-img' src='http://3.bp.blogspot.com/-Sg5t3utxRzc/UwgyzbLVAAI/AAAAAAAAFBo/vYQX0Cphx8U/s1600/indian-bride.jpg'/>
</div>
</div

Right now I am using document.getElementById("img id").getAttribute('src'; but I want this

var post = document.getElementById("post"),
var tubeimg = post.documentgetElementByTagName("img").getAttribute('src');

But tis is not working I don't know where I am getting wrongc an anyone please fix this please

I want pure javascript no jquery

Upvotes: 2

Views: 1328

Answers (3)

csuwldcat
csuwldcat

Reputation: 8249

If you wanted to get fancy:

document.getElementById('show-image').appendChild(
  new Image()
).src = document.querySelector('#post img').src;

OR

document.getElementById('show-image').innerHTML = '<img src="' + document.querySelector('#post img').src + '" />';

Upvotes: 0

adeneo
adeneo

Reputation: 318182

getElementsByTagName gets a nodeList, you need the first element in that nodeList

var post = document.getElementById("post"),
var tubeimg = post.getElementByTagName("img")[0].getAttribute('src');

querySelector has better support than getElementByTagName, so it would be easier to just do

var tubeimg = document.querySelector('#post img').src;

Which would give you

var theDiv  = document.getElementById("show-image");
var tubeimg = document.querySelector('#post img').src
var image   = document.createElement('img');

image.src = tubeimg;

theDiv.appendChild(image);

FIDDLE

Upvotes: 0

Amit Joki
Amit Joki

Reputation: 59232

Use

var tubeimg = document.getElementsByTagName("img")[0].getAttribute('src');

It returns a NodeList which you've to iterate.

Upvotes: 2

Related Questions