Max Ng
Max Ng

Reputation: 162

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.

Upvotes: 14

Views: 87562

Answers (6)

Sakhi Mansoor
Sakhi Mansoor

Reputation: 8102

Why do we need to use jQuery if we can get the img src within the document by querySelector?

Try this:

document.querySelector('[src*="Images/something.jpg"]')

P.S.: jQuery has 94 kb minified file size. Please don't include it unless there's a requirement.

Upvotes: 1

James Black
James Black

Reputation: 41858

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.

Upvotes: 41

aidanjacobson
aidanjacobson

Reputation: 2391

First, instead of using element.firstChild , use element.children[0] . Also, instead of element.getAttribute('src') , use element.src .

Hope this helps,

Awesomeness01

Upvotes: 1

Sivakumar
Sivakumar

Reputation: 1751

I know the question is asked for js which has been answered, for jquery

var image = $('#this_one img')[0];       // $('#this_one img') this will return the img array. In order to get the first item use [0]
var imageSrc = image.src;
alert(imageSrc);

It might be useful for someone who looks similarly in jquery.

Upvotes: 1

Nato
Nato

Reputation: 51

Or even simpler :

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

Works for me

Upvotes: 5

babinik
babinik

Reputation: 648

The problem is that you have the space characters between the div and img tags. That is why the first element of the div is not the image but the text - which has no method getAttribute.

You can remove spaces and use your js as it was:

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

it will be working:

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

You can get the image tag from your's div using getElementsByTagName('img') as following:

var divEl = document.getElementById('this_one'),
    src = divEl.getElementsByTagName('img')[0].src;

The above will solve your task.

More you can get from here Scripting Documents, I advise you to read this chapter.

Upvotes: 1

Related Questions