Javascript get img src and show link in a div - javascript

I'm just a beginner in javascript, I'm trying to make javascript take image src from specific image with a specific class and place the src into div.
<div class="result"></div>
<div class="ilist">
<img src="images/dog.jpg" class="thumbnail">
<img src="images/bird.jpg" class="thumbnail">
<img src="images/cat.jpg" class="selected__img"> // THIS IS THE DESIRED IMAGE
</div>
What i want to show in the result div is this = images/cat.jpg
but instead it doesn't display anything or some weird stuff...
javascript right now
var simg = document.getElementsByClassName('selected__img').src;
document.getElementsByClassName("result").innerHTML = simg;
Sorry for being such a newbie but I'm trying to learn..

The getElementsByClassName() method returns a collection of all elements in the document with the specified class name, as a NodeList object.
The NodeList object represents a collection of nodes. The nodes can be accessed by index numbers. The index starts at 0.
Try this:
<script>
var simg = document.getElementsByClassName('selected__img');
var src=simg[0].src;
var resutlObj=document.getElementsByClassName("result")[0]
resutlObj.innerHTML = src;
</script>
Full code snippet:
var simg = document.getElementsByClassName('selected__img');
var src = simg[0].src;
var resutlObj = document.getElementsByClassName("result")[0]
resutlObj.innerHTML = src;
<div class="result"></div>
<div class="ilist">
<img src="https://loremflickr.com/100/100?random=1" class="thumbnail">
<img src="https://loremflickr.com/100/100?random=2" class="thumbnail">
<img src="https://loremflickr.com/200/200?random=3" class="selected__img"> // THIS IS THE DESIRED IMAGE
</div>

getElementsByClassName is a NodeList collection. So you need to take individual nodes with [0]:
var simg = document.getElementsByClassName('selected__img')[0].src;
document.getElementsByClassName("result")[0].innerHTML = simg;
In this specifc case it's more convenient to use querySelector metod which returns one element:
var simg = document.querySelector('.selected__img').src;
document.querySelector(".result").innerHTML = simg;
or since you are using jQuery:
var simg = $('.selected__img').attr('src');
$(".result").text(simg);

$(document).ready(function() {
$('img').hover(function(){
$('.result').html($(this).attr('src'));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="result">Image path</div>
<div class="ilist">
<img src="images/dog.jpg" class="thumbnail">
<img src="images/bird.jpg" class="thumbnail">
<img src="images/cat.jpg" class="selected__img"> // THIS IS THE DESIRED IMAGE
</div>

You need to iterate over elements, since you have one selected__img you can use 0 like below:
var simg = document.getElementsByClassName('selected__img')[0].src;
document.getElementsByClassName("result").innerHTML = simg;

Related

get Attribute to insert it in my src ??, I do not know too much help me

The result that I get "undefined":
code js:
document.getElementById("myImg").src = "hackanm"+x+".gif";
var x = document.getElementsByTagName("img")[0].getAttribute("data");
HTML:
<img data="WhatIWantToAdd" id="myImg" src="" >
The ordering was wrong. Even though x is declared, it's values is used before assignment. Hence the undefined
var x = document.getElementsByTagName("img")[0].getAttribute("data");
document.getElementById("myImg").src = "hackanm"+x+".gif";
<img data="WhatIWantToAdd" id="myImg" src="" >

retrieving gifs from tenor API json

i'm implementing this tenor API into my Site....the thing is that with this function I retrieve a single value single gif...How do I foreach() all of them?
How would need to be the html structure and the javascript loop
JAVASCRIPT/ JSON
function grab_data(anon_id)
{
// set the apikey and limit
var apikey = "*************";
var lmt = 8;
.....
// callback for trending top 10 GIFs
function tenorCallback_trending(responsetext)
{
// parse the json response
var response_objects = JSON.parse(responsetext);
top_10_gifs = response_objects["results"];
// load the GIFs -- for our example we will load the first GIFs preview size (nanogif) and share size (tinygif)
document.getElementById("preview_gif").src = top_10_gifs[1]["media"][0]["nanogif"]["url"];
document.getElementById("share_gif").src = top_10_gifs[6]["media"][0]["tinygif"]["url"];
return;
}
I would have this top_10_gifs variable loaded of content...how do I foreach it?
HTML
<h2 class="title">GIF loaded - preview image</h2>
<div class="container">
<img id="preview_gif" src="" alt="" style="">
</div>
<h2 class="title">GIF loaded - share image</h2>
<div class="container">
<img id="share_gif" src="" alt="" style="">
</div>
Depends on what exactly you're trying to do (which you haven't explained), but something like
response_objects.results.forEach((gifObj, i) => {
if (i >= 8) return;
// do something with each gifObj
document.querySelector('.container')
.appendChild(document.createElement('img'))
.src = gifObj.media[0].tinygif.url;
});
to iterate over all of them.

Fetch and add img attributes to string

I have a string like this.
x = '<div class="sample">
<img src="http://www.example.com/i/java.png">
</div>
<div class="sample_another">
<img src="/i/somedir/python.png">
</div>'
I want to convert to this
x = '<div class="sample">
<img src="http://www.example.com/i/java.png" height="200px" width="100px">
</div>
<div class="sample_another">
<img src="/i/somedir/python.png" width="150px" height="150px">
</div>'
input string will be a html doc. for all the images in the doc, i want to add the height and width property. and to get the height and width property i have to use something like this
var img = new Image();
img.onload = function() {
alert(this.width + 'x' + this.height);
}
img.src = 'http://www.example.com/intl/logo.gif';
p.s. i tried using this solution but the problem i face is that the string might have the script tag and DOM parses it as a closing script tag. I cant find much for regex either. So is there any other way to obtain this result ?
Thanks.
If you can remove scripts than go with this code:
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
var string ="<script type"text/javascript"></script><img alt=''
src='http://api.com/images/UID' /><br/>Some plain text<br/><a
href='http://www.google.com'>http://www.google.com</a>";
var elem= document.createElement("div");
$(string).find('script').remove();
elem.innerHTML = string;
var images = elem.getElementsByTagName("img");
for(i=0; i<images.length; i++){
images[i].width = "150";
images[i].height = "250";
}
string = elem.innerHTML;
Problem you are facing with is that it turns out that HTML5 does not allow script tags to be dynamically added using the innerHTML property. So you will need to add them dynamically on some other way.
This is some code that might help you:
var my_awesome_script = document.createElement('script');
my_awesome_script.setAttribute('src','http://example.com/site.js');
document.head.appendChild(my_awesome_script);

Regex: Replace '&' within double quotes

I have this strange issue where URL parameter divider & of an IMG SRC gets replaced with the HTML entity.
I need to replace those so this string:
<img src="https://example.com/imagehandler?$PNG%20with%20alpha$&scl=1" alt="">
Returns:
<img src="https://example.com/imagehandler?$PNG%20with%20alpha$&scl=1" alt="">
It should only replace within double quotes — not if in other places like regular HTML entities.
A regex workaround:
var text = `<img src="https://example.com/imagehandler?$PNG%20with%20alpha$&scl=1" alt="">`;
console.log(text.replace(/src="[^"]+/g, function(match) {
return match.replace('&', '&');
}));
A DOM solution:
According to your statement, It's a string, not in the dom..., you should use DOMParser to convert a HTML string into valid DOM. Modifying #prasad's answer it would be something like this:
var HTMLmarkup = `
<img src="https://example.com/imagehandler?$PNG%20with%20alpha$&scl=1" alt="">
<img src="https://example.com/imagehandler?$PNG%20with%20alpha$&scl=1" alt="">
`
var parser = new DOMParser()
var dom = parser.parseFromString(HTMLmarkup, "text/html");
dom.querySelectorAll('img').forEach(function(a){
console.log(a.src)
})
Try with simple regex pattern /&/g .And querySelectorAll used for select the img element
Demo regex
document.querySelectorAll('img').forEach(function(a){
a.src = a.src.replace(/&/g,"")
console.log(a.src)
})
<img src="https://example.com/imagehandler?$PNG%20with%20alpha$&scl=1" alt="">
For completeness, here's a solution that uses regular DOM functions. It diverges from the original requirement in that it extracts the URL because (IMHO) it's a reasonable ultimate goal:
var html = '<img src="https://example.com/imagehandler?$PNG%20with%20alpha$&scl=1" alt=""> <img src="/some/other/location/?one=1&two=2&three=3">';
var aux = document.createElement("div");
aux.innerHTML = html;
var urls = [];
aux.querySelectorAll("img[src]").forEach(function(image){
urls.push(image.getAttribute("src"));
});
console.log(urls);

Find a element and append a image

I know how to append a image to a known tag. e.g.
//html
<div class="ImageContainer"></div>
//JS
var image = new Image;
image.src = '/Public/Images/image.png';
image.appendTo($('.ImageContainer'));
but how to find a certain tag(the figure tag here) and append the image?
I could locate the figure tag with '.find()':
var ImageContainer = $('<div><figure></figure></div>').
console.log(ImageContainer.find('figure').html());
but failed to append the image to it:
image.appendTo(ImageContainer.find('figure')); //doesn't work
If you have an image element with an id you can select it like so:
var $image = '<img src="/Public/Images/image.png" />';
Then so find the figure elemnt:
$(ImageContainer).find('figure').append($image);
Try below code.
1) Stored image url in variable name $img.
2) Find the div using class name 'image' ($('.image'))
3) Appended image to div
HTML
<div class="image"> </div>
JS
var $img = '<img src="https://skypeblogs.files.wordpress.com/2013/05/skype-button.png"/>';
$('.image').append($img);
JSFIDDLE DEMO
if you are using jquery, you can just do
var htmlString = '<div><figure><img src="some image src" /></figure></div>';
$('#ImageContainer').html(htmlString);
but if you are wanting to insert the div/figure and image separately, then you'd be best giving it some sort of identifier, i.e.
var htmlString = '<div><figure id="myFig"></figure></div>';
$('#ImageContainer').html(htmlString);
$('#myFig').html('<img src="" />');

Categories

Resources