2

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

3 Answers 3

2

Use

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

It returns a NodeList which you've to iterate.

Sign up to request clarification or add additional context in comments.

Comments

0

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

3 Comments

Can you help me further to wrap this java code inside function
@user3014202 - Help you with what exactly ?
@user3014202 - Feel free to accept one of the answers.
0

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 + '" />';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.