Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the source of an image inside a div using javascript?

Tags:

javascript

How can I get the source of an image placed inside a div with unique id.

<div id="0a01">
   <img src = "one.jpg" />
</div>
<div id="0a02">
   <img src = "two.jpg" />
</div>
<div id="0a03">
   <img src = "three.jpg" />
</div>

I know if I had given an id to the image itself I could've got it using -

var src= document.getElementById("<id-for-image>").src;

Since I can't give an id to the image tag, that makes it tricky. Not sure how get it in this case?

like image 943
ishkee Avatar asked Nov 08 '13 19:11

ishkee


People also ask

How do you reference an image in JavaScript?

In JavaScript, get a reference to the image tag using the querySelector() method. Then, assign an image URL to the src attribute of the image element.

How can we alert the SRC of first image from it in the script?

In order to get the first item use [0] var imageSrc = image. src; alert(imageSrc);

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

You can use querySelector :

var src= document.querySelector("#id-for-image img").src;

Note that the selector must be compatible with the CSS norm. That means that your id must not start with a digit.

If you really can't fix your id (which is bad because it will lead to other problems), then you can use this kind of selector :

var src= document.querySelector('[id="0a03"] img').src;

Demonstration

like image 89
Denys Séguret Avatar answered Nov 01 '22 05:11

Denys Séguret


If your layout will always be like that, you can use .children, like:

var i = document.getElementById("0a01").children[0].src;
like image 28
MikeSmithDev Avatar answered Nov 01 '22 05:11

MikeSmithDev