Reputation: 158
I have some HTML content. I want to get "foo.jpg" and store in a variable.
<div>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam interdum congue justo et facilisis. Fusce sed vulputate magna. Praesent lacinia justo ligula, a mattis enim rhoncus vitae. Quisque nec porttitor lectus. Aenean tempor magna eu egestas tincidunt. Morbi vitae mi at mauris hendrerit blandit. Nunc iaculis vitae velit at dignissim. Vestibulum vitae gravida mi. </p>
<img src="foo.jpg" alt="foo"></img>
</div>
I found this
var myimg= document.getElementById("imgid").src;
but it not will not since i dont know the image id, and because it not document but element
I trying to find something like this mycontnet.html.img[0].src
Upvotes: 1
Views: 717
Reputation: 11
You can add whatever id to your image tag like this
<img src="foo.jpg" id="myImg"/>
or
<img src="foo.jpg" id="logo"/>
then you have to use this id "myImg" or "logo" to call the image tag
var myimg= document.getElementById("myImg").src;
or
var myimg= document.getElementById("logo").src;
Try pasting this in your html file and look in the console
<img src="foo.jpg" id="myImg"/>
<script>
var myimg= document.getElementById("myImg").src;
console.log("MY IMAGE SOURCE IS "+myimg)
</script>
Upvotes: 0
Reputation: 3334
You can not get the img element because the id is not present on the
img tag. Either you can use getElementByTagName()
method or you can add id
attribute on the img tag. If you will use src
it will give you the full URL of the image if you just need the image name, you can use the getAttribute()
method.
const src = document.getElementsByTagName('img')[0].getAttribute('src');
const src = document.getElementsByTagName('img')[0].getAttribute('src');
console.log(src);
<div>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. </p>
<img src="foo.jpg" alt="foo"></img>
</div>
Upvotes: 1
Reputation: 1172
You could use any css selector to find your image using querySelector or querySelectorAll, for example.:
document.querySelector('img').src
or be more specific and modify your selector to match unique result (you could have multiple img tags at your page, so it's best to specify at least it's parent)
div > img
.image-wrapper img
img.image
Upvotes: 1
Reputation: 11416
You can use getElementsByTagName()
:
var myImg = document.getElementsByTagName("img")[0].src;
console.log(myImg);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam interdum congue justo et facilisis. Fusce sed vulputate magna. Praesent lacinia justo ligula, a mattis enim rhoncus vitae. Quisque nec porttitor lectus. Aenean tempor magna eu egestas tincidunt. Morbi vitae mi at mauris hendrerit blandit. Nunc iaculis vitae velit at dignissim. Vestibulum vitae gravida mi. </p>
<img src="foo.jpg" alt="foo" />
</div>
Upvotes: 1