Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get src of img element from div?

I want to get the src of the img element in HTML. It looks like this:

<div class="image_wrapper" id="this_one">
        <img src="Images/something.jpg" />
</div>

It's very simple when I put an ID in img, and get this src very easy.

But the problem is when I get src of img from div element.

var someimage = document.getElementById('this_one').firstChild.getAttribute("src");
alert(someimage);

I need to get this URL in string. But not worth.

like image 472
Max Ng Avatar asked Jun 23 '12 17:06

Max Ng


People also ask

What does img src => do?

The img src stands for image source, which is used to specify the source of an image in the HTML <img> tag.

How do I tag an image in a div?

1) Create a DIV tag with a unique ID; 2) Place the image into a background:url style element of a DIV tag; 3) Set the height and width properties of the DIV tag to that of the selected image.


2 Answers

Why not try something like this:

var someimage = document.getElementById('this_one');
var myimg = someimage.getElementsByTagName('img')[0];
var mysrc = myimg.src;

For more on using getElementsByTagName you may want to look at:

https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByTagName

There is some error checking I didn't do here, but I am just trying to show how you can do it.

like image 151
James Black Avatar answered Sep 23 '22 08:09

James Black


Or even simpler :

document.getElementById('yourimageID').getElementsByTagName('img')[0].src

Works for me

like image 42
Nato Avatar answered Sep 26 '22 08:09

Nato