Get src of img element from div? - javascript

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.

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.

Or even simpler :
document.getElementById('yourimageID').getElementsByTagName('img')[0].src
Works for me

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.

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.

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

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.

Related

Selecting an image element by using the source attribute to find it

I'm working on a script for a website, and I need to change the icon of one of its images. The problem is the image on the site only has a tag like this:
<img src="/pic1.png" alt="clear" >
I have tried selecting the image by using:
document.querySelector("img[src='pic1.png']");
What I have tried looks like this:
var y = document.querySelector("img[src='/pic1.png]'");
y.innerHTML = "<img src='pic2.png' alt='clear'>";
I also tried
var y = document.querySelector("img[src='/pic1.png]'");
y.src = "/pic2.png";
Is there anyway I can find the image using the src attribute, assign it to a variable, then replace the src?
Your help is appreciated :)
Your last example should work
var y = document.querySelector("img[src='/pic1.png']");
y.src = "/pic2.png";
y.load()
How about you set an Id on that element, then select it using document.getElementById(), then you can proceed to access the src property, which can help you change its value.

How to get a the url of an image from id in Javascript

I know it's such a beginner thing. So I have this image in a div with the id thumb.
<img id="thumb" src="https://url-to-a-image">
And this Javascript that it's a magnify script:
<script type="text/javascript">
var myImgSrc = document.getElementById("thumb").getElementsByTagName("img")
[0].src;
var evt = new Event(),
m = new Magnifier(evt);
m.attach({
thumb: '#thumb',
large: 'myImgSrc',
largeWrapper: 'preview'
});
</script>
As you can see I'm trying to get the image using myImgSrc and then I'm trying to use in the large: 'myImgSrc'. When I put the a fixed url in large: fixed-url-to-the-image, it works fine.
The element with #thumb id is the tag img it self, the current selector will not return the src value, so it should be simply:
var myImgSrc = document.getElementById("thumb").src;
You can get image src like this,
var thumb = document.getElementById("thumb").src;
You don't need to use getElementsByTagName.
let img = document.querySelector('#thumb');
console.log(img.src);
If you use img.src, you'll see the source of your img tag.
getElementsByTagName is superfluous - you already have the exact element you want - you selected it by its ID. You'd only need getElementsByTagName if you wanted to get one or more elements by their tag and work on them all, rather than identifying one precisely.
So actually the solution is very simple - just get the src attribute of the ID-selected element directly. Working demo:
var myImgSrc = document.getElementById("thumb").src;
console.log(myImgSrc);
<img id="thumb" src="https://url-to-a-image">

Cannot append image with jquery

I currently have a code working where i can add a class based on the url of a page using jquery. However I would like add an image to a div instead of just adding a class. I'm not as proficient in java-script as I could be but I think there is probably a pretty simple solution. The code that doesn't work is
if (window.location.href.indexOf('Locate_an_eyecare_professional') > -1) {
var img = document.createElement("img");
img.src = '~/Content/Images/Template 5A Filmstrip.jpg" />';
}
the code that works right now that I dont want to use is
if (window.location.href.indexOf('Locate_an_eyecare_professional') > -1) {
var $body = $('body');
$body.addClass('campaign');
}
How can apply what I do know that works to what I am trying to get to work?
If for some reason you don't want to use jQuery for this part, you just need to append the element to the body of the html document (or wherever you want it to end up) like so:
Javascript Code
if (window.location.href.indexOf('Locate_an_eyecare_professional') > -1) {
var body = document.getElementsByTagName("BODY")[0];
var img = document.createElement("img");
img.className = 'img-responsive'
img.src = '~/Content/Images/Template 5A Filmstrip.jpg';
body.appendChild(img);
}
You can add a <img> to any element using the jQuery .append() function in the following way:
var imageToAppend = '<img src="http://example.com/img.png" height="200" width="200"/>';
$('#myElementId').append(imageToAppend); //This will append you HTML to the div with id "myElementId"
You can read more about this here: http://api.jquery.com/append/
Happy coding! =]
You should use the element where you need to append (prepend) the image element so the code will look something like:
$("base element selector").append(img);
but you need to consider that the address of the image source may not be correct from the browser point of view - consider the page is hosted in application like http://server.com//applicationgroup/applicationroot/Content/Images/.....jpg may not be pointed with ~/Content/Images/.....jpg you rather need to translate the address to the full server address on the server side.
In my case I just had to remove "~" from:
<img src="~/assets/icons/ic_chevron2.svg" class="rot-90" />
resulting in:
<img src="/assets/icons/ic_chevron2.svg" class="rot-90" />

Get an attributes value of the ALT attribute of a hyperlink

My a-tag (link) contains innerHTML which is an image like this:
.innerHTML = <img alt="hello world" src="/Content/Images/test.png">
How can I get the text of the alt attribute with JQuery?
You really don't need jQuery. If you have the a element you can do this:
// lets call the anchor tag `link`
var alt = link.getElementsByTagName('img')[0].alt; // assuming a single image tag
Remember attributes map to properties (most), and unless the property is changed, or the attribute, the two should reflect the same data (there are edge cases to this, but they can be handled case-by-case).
If you truly do need the attribute there is
var alt = link.getElementsByTagName('img')[0].getAttribute('alt');
Last scenario is if you only have the image tag as a string.
var str = '<img alt="hello world" src="/Content/Images/test.png">';
var tmp = document.createElement('div');
tmp.innerHTML = str;
var alt = tmp.getElementsByTagName('img')[0].alt;
If you must use jQuery (or just prefer it) then the other answer provided by Alexander and Ashivard will work.
Note: My answer was provided for completeness and more options. I realize the OP asked for jQuery solution and not native js.
Being $a your <a/> element.
Using jQuery you can do:
$("img", $a).first().attr("alt");
Or, using pure JavaScript:
var $img = $a.getElementsByTagName("img")[0];
console.log($img.alt);
​
See it here.
use this.
var altName=$('a img').attr('alt');

Javascript : get <img> src and set as variable?

If the img below is present
<img id="youtubeimg" src="http://i1.ytimg.com/vi/VK4ah66jBvE/0.jpg"/>
and the script is
<script>
var youtubeimgsrc = "something here"
document.write(''+youtubeimgsrc+'')
</script>
and the result should be http://i1.ytimg.com/vi/VK4ah66jBvE/0.jpg
what can i do to get the image source and set as a variable.
As long as the script is after the img, then:
var youtubeimgsrc = document.getElementById("youtubeimg").src;
See getElementById in the DOM specification.
If the script is before the img, then of course the img doesn't exist yet, and that doesn't work. This is one reason why many people recommend putting scripts at the end of the body element.
Side note: It doesn't matter in your case because you've used an absolute URL, but if you used a relative URL in the attribute, like this:
<img id="foo" src="/images/example.png">
...the src reflected property will be the resolved URL — that is, the absolute URL that that turns into. So if that were on the page http://www.example.com, document.getElementById("foo").src would give you "http://www.example.com/images/example.png".
If you wanted the src attribute's content as is, without being resolved, you'd use getAttribute instead: document.getElementById("foo").getAttribute("src"). That would give you "/images/example.png" with my example above.
If you have an absolute URL, like the one in your question, it doesn't matter.
How about this for instance :
var youtubeimgsrc = document.getElementById("youtubeimg").getAttribute('src');
If you don't have an id on the image but have a parent div this is also a technique you can use.
<div id="myDiv"><img src="http://www.example.com/image.png"></div>
var myVar = document.querySelectorAll('#myDiv img')[0].src
in this situation, you would grab the element by its id using getElementById and then just use .src
var youtubeimgsrc = document.getElementById("youtubeimg").src;
var youtubeimgsrc = document.getElementById('youtubeimg').src;
document.write(youtubeimgsrc);
Here's a fiddle for you http://jsfiddle.net/cruxst/dvrEN/
Use JQuery, its easy.
Include the JQuery library into your html file in the head as such:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
(Make sure that this script tag goes before your other script tags in your html file)
Target your id in your JavaScript file as such:
<script>
var youtubeimcsrc = $('#youtubeimg').attr('src');
//your var will be the src string that you're looking for
</script>

Categories

Resources