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

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>

Related

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">

change some text in src of image tag using jquery [duplicate]

This question already has answers here:
Changing the image source using jQuery
(17 answers)
Closed 4 years ago.
I want to change one letter in the src of the image tag using js or jQuery.
<img src="/media/image_i/ball.png">
<img src="/media/image_i/bat.png">
I want to change that letter i in the src to a number.
Eg.it should look like this -
<img src="/media/image_4/ball.png">
<img src="/media/image_4/bat.png">
EDIT- When i used the solutions everything was working, but it was changing the "src" of all image tags to same as first image, so the second image which is "bat.png" is getting changed to "ball.png", so same image is displaying two times.
Thank you!
You can simply get the src attribute of the images, loop it over and replace the _i with _4 using JQuery. To check the below snippet works, you need to use inspect element of the browser and check the src attribute.
$(document).ready(function(){
$('img').each(function(){
var src = $(this).attr('src');;
$(this).attr('src', src.replace('_i','_4'));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="/media/image_4/ball.png">
<img src="/media/image_4/bat.png">
You can do this job using regex.
$(document).ready(function(){
var src = $('img').attr('src');
var newsrc = src.replace(/_./g, '_4');
$('img').attr('src', newsrc);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="/media/image_i/ball.png">
You can develop it further.
For more : https://stackoverflow.com/a/2912904/5792209
First, you'll need to identify the particular img element you need to modify. This can be done in a variety of ways, like giving the img in question an id or a class that is unique. If the image is the only one using the src you've specified in your question, you can use that (and that's what I'm doing in the code that follows).
After getting the proper reference to the element, use the .attr() method to get/set the current src value and the standard String.replace method to swap the values:
var current = $("img[src='/media/image_i/ball.png']");
current.attr("src", current.attr("src").replace("_i", "_4"));
If this is all you need to do, JQuery is overkill. Standard JavaScript is just as simple:
var el= document.querySelector("img[src='/media/image_i/ball.png']");
el.src = el.src.replace("_i", "_4");

Get src of img element from div?

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.

Retrieve attributes from the tag that imported the script

<script data-src="scripts/" src="scripts/myscript.js"></script>
from within myscript.js how do i retrieve data-src? assume that there are also a lot of scripts loaded in the same format as this and that myscript.js does not know anything besides the fact that it's going to get the attribute data-src
is this possible?
You could do it like this because your script will be the last script element found by getElementsByTagName(), until the next script is loaded when that one will become the last and so on.
var scriptList = document.getElementsByTagName('script');
var me = scriptList[scriptList.length-1];
var mySrc = me.getAttribute('data-src');
If its the data-src attribute of a particulr script tag, I'd put an Id on the tag, and get it through the Id.
<script id='DataSrcScript' data-src="scripts/" src="scripts/myscript.js"></script>
var dataSrc = document.getElementById('DataSrcScript').getAttribute('data-src');

Javascript: replace a string in element.src attribute

Hi I am currently trying to replace a query string value in a a link's src attribute.
it works fine in firefox but not in ie.
example:
<a id="link" href="#" src="http://somedomain.com?id=123&size=20">link</a>
then on my js it looks kinda like this:
var link = document.getElementById('link');
link.src.replace('size=20', 'size=45');
in ie, it returns something like src is not an object error;
anyone kind enough to lend a hand?
also, i need this to be on native javascript so please don't suggest a framework as a solution thanks.
To get it to work in IE you're going to need to use link.setAttribute('src', ...).
use:
var link = document.getElementById('link');
var src = link.getAttribute("src").replace('size=20', 'size=45');
link.setAttribute("src", src);
Well, links (anchor elements) don't have a src attribute, I think that you want to change the href attribute:
var link = document.getElementById('link');
link.href = link.href.replace('size=20', 'size=45');
In your case the "src" attribute in your link is an expando attribute, since an anchor tag does not have a src.
When working with expando attributes, it's safest to set and get the values using the setAttribute('attributeName',***value*)** and getAttribute('attributeName') accessors.
To find out more about getAttribute and setAttribute you can check here:
https://developer.mozilla.org/en/DOM/element.getAttribute
https://developer.mozilla.org/en/DOM/element.setAttribute
To find out more about DHTML properties you can check the MSDN Resource here:
http://msdn.microsoft.com/en-us/library/ms533055%28VS.85%29.aspx
Example Code using getAttribute and setAttribute:
var link = document.getElementById('link');
var src = link.getAttribute('src');
link.setAttribute('src',src.replace('size=20','size=40'));
I believe getAttribute is more cross-browser friendly.
var link = document.getElementById('link');
var result = link.getAttribute("src").replace('size=20', 'size=45');
Also, the replace function returns a string. It doesn't operate on the string it is called against. This means you have to assign the result.
link.setAttribute("src", result);

Categories

Resources