Problem:
Trying to add image src to array without the website URL (http://).
HTML code:
<img src="images/pink.jpg" alt="Photo" class="pink">
JS code:
var photoArray = [];
photoArray.push(this.parentNode.getElementsByTagName("img")[0].src);
alert(JSON.stringify(photoArray));
Desired result:
http:// and so on adds to the array but all I want the array to save is "images/pink.jpg" without any http:// beginning.
Use .getAttribute('src') instead. It will fetch exactly what you need.
Working Code Snippet:
var photoArray = [];
photoArray.push(document.getElementsByTagName("img")[0].getAttribute('src'));
alert(JSON.stringify(photoArray));
<img src="images/pink.jpg" alt="Photo" class="pink">
Readup: .getAttribute() | MDN
This is because the browser expands the src property to the full URL. Use getAttribute to the the attribute value instead of the expanded src property.
this.parentNode.getElementsByTagName("img")[0].getAttribute('src')
Related
im trying to store an image in HTML that comes from a url source in a variable using JavaScript. Could someone show me what code is required? i have started it off...
var productImage = document.getElementById("productImg").//??;
<img id="productImg"
src="https://i5.walmartimages.com/asr/1735db1c-d84f-417a-b871-27b63ee2b2e6_1.9a18f15c0e0fa321d0c5d073875b9738.jpeg?odnWidth=undefined&odnHeight=undefined&odnBg=ffffff" >
You were close. To obtain the value of an HTML element's attribute, you can access that attribute as a property of the DOM element.
var productImage = document.getElementById("productImg").src;
console.log(productImage);
<img id="productImg"
src="https://i5.walmartimages.com/asr/1735db1c-d84f-417a-b871-27b63ee2b2e6_1.9a18f15c0e0fa321d0c5d073875b9738.jpeg?odnWidth=undefined&odnHeight=undefined&odnBg=ffffff" >
You can use the src property.
var productImage = document.getElementById("productImg").src
You can also use the src property to set a new URL for the image if you want to replace it.
var productImage = document.getElementById("productImg");
productImage.src = URL
I have a page where the following pattern happens quite often:
<a href="path/to/image.jpg">
<img src="path/to/image.jpg">
</a>
In order to avoid typos, I'd prefer to only have to enter the image and path once.
Is there a way (preferably using only native HTML/JS/CSS) to avoid that duplication?
Only recent browsers need to be supported.
Edited to add: there's one location in the page that has a similar but possibly conflicting pattern:
<a href="https://a.web.site/">
<img src="image.jpg">
</a>
I could get rid of it if needed.
But maybe a more robust solution would be to start from something like:
<a href="path/to/image.jpg">
IMG_LINK_TO_CREATE
</a>
and to replace a predefined pattern with the img tag, rather than the other way around.
To fit my answer to your question, I'll only use Vanilla JavaScript. Also, since it's not clear for me if you are trying to create an img from an anchor or viceversa, I am doing both for you. I'll put first the one that appears in you question title.
Identify your elements:
If you want this to work, you need to give at least a class or unique id attribute to your anchor tag in order to properly modify it later on when they are loaded into the DOM.
Generate anchor tag for an image tag
For this case, since you probably will be using multiple anchors and you'll have to do the same for every anchor you want, a class attribute with "create-link" would be enough for you to easily modify these elements directly from the DOM. Something like this would help:
<img class="create-link" src="path/to/image.jpg">
With this said, you can create a function called generateImages() which will do all the work.
function generateImages(){
let images = document.querySelectorAll(".create-link");
images.forEach(image=>{
let link = document.createElement('a'),
parent = image.parentNode,
childImage = new Image();
link.href = image.src;
link.classList.add('generated-link');
childImage.src = image.src;
link.append(childImage);
image.parentNode.removeChild(image);
parent.append(link);
});
}
And that should do it. You can now just execute it whenever you want or in the window load event.
window.onload = generateImages;
Here is a fiddle to help you visualize the overall of this method.
https://jsfiddle.net/m90b6vc5/1/
Generate image from anchor tag:
Same thing as the other one, identify your elements that you will need to use in JavaScript in the future.
The code would be a little bit easier to this, just need to retrieve the link from the anchor tag and append it to a new image element:
function generateImages(){
let a = document.querySelectorAll(".create-link");
a.forEach(element=>{
let image = new Image();
image.src = element.href;
element.append(image);
});
}
https://jsfiddle.net/m90b6vc5
You can do this. But note that this only adds the img after the page is loaded. which means the users view can be re-rendered after the page loads. You can control it to some extent by defining the expected img with-height or ratio in the .img-link class using css
$(document).ready(function(){
$('.img-link').each(function(){
$(this).append($('<img src="' + $(this).attr('href') + '" />'));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<a href="custom-link">
<img src="custom-image.jpg" />
</a>
javascript function
function createImageStructure(number, imageArray){ var structure = "";
for(var i = 0; i < number; i++){
structure += ' <img src="'+imageArray[i]+'"> ';
} console.log(structure); }
var imageArray = [];
imageArray.push("https://pay.google.com/about/static/images/social/knowledge_graph_logo.png");
imageArray.push("https://pay.google.com/about/static/images/social/knowledge_graph_logo.png");
createImageStructure(2, imageArray);
output
<img src="https://pay.google.com/about/static/images/social/knowledge_graph_logo.png"> <img src="https://s23527.pcdn.co/wp-content/uploads/2018/05/google-photos.png">
basically, create a function, create an array, to have image paths, this will help to create HTML structure with multiple images.
if need more help please let me know, i will fix this, if you want just one image source path for all img tags
While I really don't want to encourage you to do this with client-side code, I will at least suggest you use code that generates links instead of code that generates images. This way, the website still shows images if the JS doesn't run.
The simplest way to do this is to add a class to all images which you want to automatically wrap in a link, such as "auto-link", and then run this code:
for (const img of document.querySelectorAll(".auto-link")) {
const link = document.createElement("a");
link.href = img.src;
img.parentElement.replaceChild(link, img);
link.appendChild(img);
}
You can put this in an "domready" or "load" event listener, or just in a script tag at the end of the page.
Note that pretty much all browsers have a "view image" option in their context menu, so there's no reason to do this. You shouldn't introduce a dependency on JavaScript, which slows down execution and wont work if you disable JS or use a screen reader. Instead, features like these ought to be done server-side or as a compilation step.
A good way to encapsulate your html and reuse it elsewhere is React.
function AImg({ href, src }) {
return <a href={ href || src }>
<img src={ src }/>
</a>;
}
ReactDOM.render(
<div>
<AImg src="https://placecage.com/./200/200" />
<AImg src="https://placecage.com/c/200/200" href="https://placecage.com"/>
<AImg src="https://placecage.com/g/200/200" />
</div>,
document.getElementById('aimg_container')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="aimg_container"></div>
React.js is good way to go. If you want to still use ES6 only you can use also backticks. Add links to images and links in an array and in a for of loop create links with image. Something like:
const urls = ['1', '2', '3'];
const images = ['a','b','c'];
let links = [];
for (let index of urls.keys()) {
links.push(`
<img src="${images[index]}" />
`);
}
Adding elements to the DOM can be expensive. I would not be adding a tags via javascript. Keep your HTML mostly as is, but leave the href attribute empty for the links you want to populate.
I've also given you the option of populating the image source based on the href. This is not as good as the image has to be loaded after the page is rendered.
//Wait for everything to be loaded
document.addEventListener("DOMContentLoaded", function(){
//Find a tags with empty hrefs
let emptyAs = document.querySelectorAll("a[href='']");
emptyAs.forEach((a) => {
//Update href based on image src
a.href = a.querySelector("img").src;
});
//Alternatively Find images with empty src
let emptyImgs = document.querySelectorAll("img[src='']");
emptyImgs.forEach((img) => {
img.src = img.parentNode.href;
});
});
<a href="">
<img src="https://fillmurray.com/200/200" />
</a>
<a href="">
<img src="https://fillmurray.com/100/100" />
</a>
<a href="https://fillmurray.com/300/300">
<img src="" />
</a>
<a href="http://www.google.com">
<img src="https://fillmurray.com/400/400" />
</a>
Note forEach has no IE support for a node list: https://developer.mozilla.org/en-US/docs/Web/API/NodeList/forEach
Here is the div:
<div id="img-container">
<img id="upSlika" src="#"/>
</div>
And this is the JSON response:
{"pictureUrl":"url"}
How can I change image's source to URL received in response above?
Suppose that your json is stored in the following variable json:
var json = {"pictureUrl": "url"};
With the following code, what you do is to set the attribute src to the element img with id="upSlika":
$("#upSlika").attr("src", json.pictureUrl);
You can check the documentation jQuery ID Selector and jQuery .attr()
You can change the image's src in jQuery by using attr() function.
See the documentation.
Try the code bellow:
//get the json to data variable
var data = {"pictureUrl":"url"};
$("#upSlika").attr("src", data.pictureUrl);
I have a html snippet being returned through ajax. The snippet is an <img> tag.
<img src="image.jpg" />
I need to extract the value of the src attribute without loading the image initially. The reason for this is the src attribute contains a partial path that I need to manipulate in my app to load the image properly.
I have the following code currently extracting the src attribute:
var src = $(value).attr('src');
However, this causes the image to load, resulting in a 404. I would like to avoid this unnecessary request.
How can I extract the value of the src attribute without causing the browser to load the image?
I solved this by changing the name of the src attribute before loading it into jquery.
value = value.replace('src', 'data-src');
var src = $(value).attr('data-src');
Doing this allows me to extract the value without causing the browser to attempt to load the images.
Your best bet is probably to output a data tag on the image. You can then manipulate this using jQuery and then use it to write the final image path.
So you'd do something like this in your HTML:
<img data-img-src="abc.jpg" class="my-image" />
Then in your jQuery:
var path = $('.my-image').data('img-src');
console.log(path); // Do something here, then write the new path with:
$('.my-image).attr('src', new_path);
EDIT: Sorry I just re-read the bit where it's coming via AJAX. In that case, you can probably use the data callback of your ajax request to strip the src from the image.
$.ajax('someURL.html', function(data){
var html = data.replace(/\ssrc/g, ' data-src'),
img = $(html),
src = 'some/path/' + img.data('src');
img.attr('src', src);
$('#container').append(img);
});
If you just have the string , like <img src="image.jpg" /> why dont you go for regex?
Something like: /[\"\'][a-z0-9A-Z\.]*/.
PS:My regex skills are poor,so you could manipulate it accordingly.
Use
var string = '<img src="image.png">';
var matches = string.match(/src\=("|')(.*?)\1/);
console.log(matches[2]);
You can simply remove the attribute after accessing it.
This will not load the invalid image, as you can confirm in your console:
var s= $('<img src="invalidURL.jpg">'),
src= s.attr('src');
s.removeAttr('src');
console.log(src);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Remove removeAttr(), and it will attempt to load the image.
I am building a lightbox, in pure JavaScript. I currently have my images loading via AJAX, but i know it is easier to just have the img data-src attribute being replaced onclick to src.
I however have NO idea how this is done in pure JavaScript, by that i mean, without using any libraries.
Can anyone tell me how this is done?
to sum up: How do i change ex:
<img data-src="URL"/>
to:
<img src="URL"/>
without jQuery.
You can do it like shown below:
var imgEl = document.getElementsByTagName('img');
for (var i=0; i<imgEl.length; i++) {
if(imgEl[i].getAttribute('data-src')) {
imgEl[i].setAttribute('src',imgEl[i].getAttribute('data-src'));
imgEl[i].removeAttribute('data-src'); //use only if you need to remove data-src attribute after setting src
}
}
The above code will fetch all img tags, check if they have a data-src attribute and if present, replace it with src.
Demo Fiddle
Get a handle on the image element, and then set it's src property, using the value from getAttribute().
Plain Javascript doesn't have any helper functions to handle data-* attributes, it just treats them as any other attribute.
var img = document.getElementById("myimg");
img.src = img.getAttribute("data-src");
You can use forEach with querySelectorAll
var imageElements = document.querySelectorAll('img');
imageElements.forEach(c=> c.setAttribute('src',c.getAttribute('data-src')));
img{width:100px;}
<img data-src='https://cdn4.iconfinder.com/data/icons/nature-20/512/79-512.png' />