gonzalo2000 gonzalo2000 - 1 year ago 49
HTML Question

image API src into <img> with jquery

I'm starting out with jquery and json, working on a weather app using OpenWeatherMap's API. I'm trying to pass an icon src to be displayed with an img tag. I understand something analogous has been asked before (which was my model for the code below), but I'm not seeing a change in upon inspection.

In my view I have

<img id="icon" src="#">
, and this is my jquery:

$(document).ready(function() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var lati = position.coords.latitude;
var longi = position.coords.longitude;
var address = "http://api.openweathermap.org/data/2.5/weather?lat=" + lati +"&lon=" + longi + "&APPID=****";

$.getJSON(address, function(json) {
var iconSrc = "http://openweathermap.org/img/w/" +json.weather.icon +".png";
$('#icon img').attr('src', iconSrc);

Answer Source

$('#icon img').attr('src', iconSrc); selection is not the correct one for your example

you are trying to select an img element that is a child of an element with id icon #icon

select only with the id

$('#icon').attr('src', iconSrc);

Remember id's should be unique, so if you have multiple img tags to populate use classes