Learn the steps to assign a Base64 URL to an image source

I am currently facing an issue with an image that is being used with angular-cli:

<img src="" style="width: 120px; padding-top: 10px" alt="" id="dishPhoto">

The image has a Base64 url named imgUrl. My intention is to set the image source using the following code:

let img = document.getElementById('dishPhoto');
img.setAttribute('src', this.imgUrl);

However, I encounter an error:

document.getElementById(...) is null

I would appreciate any assistance in resolving this issue. Thank you.

Answer №1

It's important to ensure that your code runs after the element has been loaded (if your script is within the <head> tag, the element does not yet exist).

If the necessary data metadata for images is not already present, you will need to add it: data:image/png;base64, (reference on including images in CSS).

Below is a functional example:

var imageData = 'iVBORw0KGgoAAAANSUhEUgAAACEAAAAhCAYAAABX5MJvAAAABHN...';

var img = document.getElementById('dishPhoto');
img.src = 'data:image/png;base64,' + imageData;
<img src="" id="dishPhoto">

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to trigger useEffect when the state being used within the effect is expected to change during the course of the effect's

Exploring the following code snippet: const [list, setList] = useState([]); const [curPage, setCurPage] = useState(0); const fetchItem = useCallback(async ()=>{ const data = await callAPI(); // data is an object setList(prev => [...prev, data]) ...

modifying the state in a stateless React component

Hello everyone! I am here trying to work with hooks and I'm not sure how to achieve my goal. Here is the code I have: import React, { useState } from 'react' import { useForm } from 'react-hook-form' import {useDispatch } from &a ...

Receiving NULL data from client side to server side in Angular 2 + Spring application

I'm currently working on a project that involves using Angular 2 on the client side and Spring on the server side. I need to send user input data from the client to the server and receive a response back. However, I'm encountering an issue where ...

Adding several <div> elements with the correct indices

I need help with a dynamic form that requires users to select a state before revealing the corresponding cities within that state. <form method="post"> <div class="summary"> <div class="trip"> <select name="State" class="s ...

Exploring the world of Vue and Pinia: managing and accessing data like

While delving into Vue and Pinia, I encountered a data management issue on the user side. On my main page, I showcase categories and auction items. However, upon navigating to a specific category in the catalog, the data for auction items remains in the st ...

Looking for assistance in streamlining JavaScript for loops?

I am currently working on a project involving a random image generator that displays images across up to 8 rows, with a maximum of 240 images in total. My current approach involves using the same loop structure to output the images repeatedly: var inden ...

Nested Tab Generation on the Fly

My goal is to create dynamically nested tabs based on my data set. While I have successfully achieved the parent tabs, I am encountering an issue with the child tabs. Code $(document).ready(function() { var data1 = [["FINANCE"],["SALE"],["SALE3"]]; var da ...

I am attempting to adjust the color of the active tab, but I seem to be encountering issues in my code. Can anyone help me

The currently active tab should change along with the text inside the box, but it's not working as expected. I'm struggling to find out why. Here is a fiddle to demonstrate my progress so far: var btn1 = document.getElementById("btn1"); va ...

Why does the error message "DeprecationWarning: 'originalKeywordKind' deprecated" keep popping up while I'm trying to compile my project?

Upon completing the compilation of my project, I encountered the error message provided below. What does this signify and what steps can I take to resolve it? - info Linting and checking validity of types DeprecationWarning: 'originalKeywordKind' ...

Map Loader for GeoJson Leaflet Integration

Although my English skills are not perfect, I will do my best to explain my issue. I have some knowledge of javascript / html / ajax and I have created a webgis using Leaflet. The problem arises when loading a large geojson file onto the map - it takes qui ...

Save unique pairs of keys and values in an array

I'm faced with extracting specific keys and values from a JSON data that contains a variety of information. Here's the snippet of the JSON data: "projectID": 1, "projectName": "XXX", "price": 0. ...

Having trouble with the "initSdk" property being undefined in your React Native Appsflyer integration?

I'm currently facing an issue while trying to integrate AppsFlyer into a react native application. The error I am encountering is "Cannot read property 'initSdk' of undefined" Initially, I imported the react-native-appsflyer module as shown ...

What are strategies for handling intricate state logic within my Vue.js checkbox component?

I'm facing a few challenges as I dive into learning Vue.js for just one week. Keep in mind that this example is actually nested within a parent component called <question>, but for the sake of simplicity, I've streamlined the code for this ...

Transform the angular code in order to execute innerHTML functions

function campform() { $.ajax({url: "{{ path('campform') }}", success: function(result){ $("#respuesta").html(result); }}); } I am having trouble with the angular code in the result I received. Can anyone provide guidance on how t ...

Encountered an error when trying to access the 'modules' property of undefined in the /node_modules/bindings/bindings.js file while working with electron and setting up

1. npm install -g node-gyp 2. npm install serialport -S 3. npm install electron-rebuild -D 4. ./node_modules/.bin/electron-rebuild.cmd and after that, the rebuild process is completed. When I execute the command: npm run electron:serve, I encounter an ...

Is there a way to allow users to edit all the input fields within the td elements when they click the edit button for a specific row?

I am completely new to web dev and I'm struggling with what should be a simple task. My goal is to enable editing of all inputs in a table row when the edit link is clicked. Since I am not using jQuery, I prefer a pure JavaScript solution if possible. ...

When trying to append in jQuery, the error "JQuery V[g].exec is not a

Attempting to create a script that adds a table to a div within the website using the following function: function generateTable(container, data) { var table = $("<table/>"); $.each(data, function (rowIndex, r) { var row = $("<tr/>"); ...

Using jQuery, you can disable an option upon selection and also change its border color

learn HTML code <select name="register-month" id="register-month"> <option value="00">Month</option> <option value="01">January</option> <option value="02">February</option> <option value="03"& ...

I am experiencing difficulties with the React-router useHistory function

Currently working on a project involving react and nodejs. Utilizing window.location.href to redirect to another page upon successful login, however, attempting to use useHistory for redirection without updating is yielding an error message: Error Uncaugh ...

Unpredictable Redirection when URL is Clicked using PHP or Javascript

Looking to send users to a random URL from a specific list? For instance: With 3 URLs available - Google.com, Facebook.com, and Yahoo.com <a href="<?php $sites[array_rand($sites)] ?>">Click here</a> Upon clicking the link, users will ...