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?
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.
In order to get the first item use [0] var imageSrc = image. src; alert(imageSrc);
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.
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
If your layout will always be like that, you can use .children, like:
var i = document.getElementById("0a01").children[0].src;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With