Get src of img element from div?
I want to get the src of an img element in HTML. It looks like this:
<div class="image_wrapper" id="this_one"> <img src="Images/something.jpg" /> </div> It is very simple when I put the ID in img and get this src very simple.
But the problem is that I get src from img from the div element.
var someimage = document.getElementById('this_one').firstChild.getAttribute("src"); alert(someimage); I need to get this URL in a string. But not worth it.
Why not try something like this:
var someimage = document.getElementById('this_one'); var myimg = someimage.getElementsByTagName('img')[0]; var mysrc = myimg.src; For more information on how to use getElementsByTagName, you can see:
https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByTagName
There is some error checking that I did not do here, but I'm just trying to show how you can do this.
Or even simpler:
document.getElementById('yourimageID').getElementsByTagName('img')[0].src Works for me
The problem is that you have spaces between div and img tags. That's why the first div element is not an image, but text - which does not have a getAttribute method.
You can remove the spaces and use your js as is:
<div class="image_wrapper" id="this_one"><img src="Images/something.jpg" /></div> he will work:
var someimage = document.getElementById('this_one').firstChild.getAttribute("src"); alert(someimage); You can get the image tag from your div using getElementsByTagName('img') as follows:
var divEl = document.getElementById('this_one'), src = divEl.getElementsByTagName('img')[0].src; The above solution to your problem.
You can get more details from the Scripting documentation here, I advise you to read this chapter.
I know that the question about js 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); This may be useful for those who look similar in jquery.
First, use element.children[0] instead of element.firstChild . Also, use element.getAttribute('src') instead of element.getAttribute('src') .
Hope this helps,
Awesomeness01