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

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.

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

Getting image source from image element using $(this).find("");

I'm currently stuck trying to get the image source (eg: ./imgs/image.jpg) from an image element.
I've managed to get it working, partially, by using the following:
var image = document.getElementById("home-our-doughnuts-box-image").getAttribute("src");
But I need to use $(this).find("#MY_IMAGE_ELEMENT_ID_HERE").getAttribute("src"); so it references the correct box and image (I have multiple containers with elements in them that share the same ID, same with the box).
So how can I access the images src attribute to return the unresolved path using $(this).find(), as it's not working ?
Thank you.
EDIT
I am using this because I have assigned a click function to each of the boxes. So need to use $(this) to reference that particular box.
Full Code:
box.onclick = function() {
var image = $(this).find("#home-our-doughnuts-box-image").getAttribute("src");
alert(image);
doughnutExpandedName.text($(this).find("#home-our-doughnuts-box-name").text());
doughnutExpandedDesc.text($(this).find("#home-our-doughnuts-box-desc").text());
};
Try this:
var src = $(this).find("#MY_IMAGE_ELEMENT_ID_HERE").attr("src");

Change the background image of an element

So I'm having some issues with creating a really simple function that's supposed to change the background image of a div element to match whatever image is being hovered upon by the mouse.
The HTML looks like
<div id = "image">
Hover over an image below to display here.
</div>
<img class = "preview" alt = "Styling with a Bandana" src = "https://s3-us-west-2.amazonaws.com/s.cdpn.io/389177/bacon.jpg" onmouseover = "upDate(this)" onmouseout = "unDo()">
That's just the div element I want to change, alongside one of the images.
So our function is supposed to take in an image element as a parameter. But I'm having a lot of trouble accessing this image parameter's src attribute and using that in the .style.backgroundImage property.
My current code is:
function upDate(previewPic){
var div_element = document.getElementById('image').innerHTML;
var picurl = "url(previewPic.getAttribute('src'))"
div_element.style.backgroundImage = "url(picurl)";
}
And this gets me an error of Uncaught TypeError: Cannot set property 'backgroundImage' of undefined on my browser console.
If you can tell, I'm trying to put the actual div object into a variable, then put the picture url into a variable. Then I want to use the .style.backgroundImage property. This isn't working. But the solution is probably really simple. What could I do to fix it?
There are multiple issues with your code.
Getting the inner html is just setting your variable to a string representation of what's inside the element, which is nothing since it's an <img> tag.
Essentially, you're putting everything in quotes, so javascript doesn't do anything with it.
Remove the .innerHTML from the first line of the function, and then take the parts javascript needs to evaluate as code out of the quotes.
Change your code to:
function upDate(previewPic){
var div_element = document.getElementById('image');
var picurl = "url(" + previewPic.getAttribute('src') +")"
div_element.style.backgroundImage = picurl;
}
This should work.
If I understand on some image hover you want to change div background?
I would do it with jquery:
$('img').hover(function(){
$('div').css(''background-image:'url("image_link")');
});

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

Categories

Resources