Setting the image path using setAttribute in JavaScript: A step-by-step guide

Trying to establish a pathway to an image in my local storage using a setAttribute approach seems to be resulting in an error indicating that the image cannot be found. Here is a snippet of the code I am working with:

if (shipLocation[0][0] == shipLocation[1][0] && i == 0) {
    var x = document.createElement("IMG");
    x.setAttribute("src", "../assets/patrolBoatHorizontalView.png"); // THIS IS THE PATH

}

Error

GET http://localhost:8081/assets/patrolBoatHorizontalView.png 404 (Not Found)

I am uncertain if this method of specifying the path is correct. I am using VisualStudio Editor and all my images are stored in the assets folder, and the request is being made from one of the components in this VueJS App.

Any suggestions or advice on this matter?

Answer №1

One way to load an image during the build process is by using the require method. When using Webpack, it will handle the loading of the image.

For example:

if (shipLocation[0][0] == shipLocation[1][0] && i == 0) {
  var x = document.createElement("img");
  let image = require("../assets/patrolBoatHorizontalView.png");
  x.setAttribute("src", image); 
}

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

Error: Unrecognized primary operator: $sortby

We have a web application built using Node.js and Mongoose, running on Ubuntu Linux servers hosted on DigitalOcean VPS. One of our Mongoose queries includes a text index with the following operators: less than / equal to limit order by This is how the ...

What steps do I need to take in order to create a histogram with perfect symmetry?

I am looking to create a unique JavaScript program that can generate a symmetric histogram resembling the image provided below: This program will prompt the user to input the number of bars they want to display and specify the character used to draw the b ...

What is the easiest method to transfer a variable from Express to Vue.js?

Hey there! I'm currently diving into Vue.js and finding it quite challenging compared to using EJS. I'm struggling with passing res.locals.something from my Express server to my Vue frontend. Specifically, I am working with Passport.js for user a ...

Perhaps dividing numbers with regular expressions

My HTML textarea allows users to input numeric serial numbers in various formats - either inline, separated by any character, or in columns from an Excel file. The serial codes are either 14 characters long if the first character is "1," or always 15 char ...

Guide to showcasing an Expo camera image in a React Native app

I have been working on an app that involves camera functionality. I have successfully taken a picture and converted it into base64 format. However, I am facing an issue when trying to display the image. Can someone please assist me in achieving this goal? ...

What is the reason for `then` generating a new promise rather than simply returning the promise that was returned by `

I've been curious about why, in a situation where the onFulfilled handler of then() returns a promise p2, then() creates a new promise p3 instead of simply returning p2? For example: let p1 = new Promise(function(resolve, reject) { resolve(42); ...

Get the Vue PDF now!

Whenever I use this function in Postman, the PDF is downloaded successfully. However, when I try to call it from the page, the request is made but the download does not happen. I really need it to be able to download. ,generateFarmerPDF:function (id) { ...

What is the proper method for overriding styles in material-ui v5 for properties that are not present in the themes components?

Currently, I am customizing MuiDataTables using the adaptv4theme in the following manner: declare module '@material-ui/core/styles/overrides' { export interface ComponentNameToClassKey { MUIDataTable: any; MUIDataTableFilterList: any; ...

Issue with downloading files in Internet Explorer is not functioning properly

I am encountering an issue in my Angular.js controller where downloading a CSV file works perfectly in Chrome but not in IE. The browser console log indicates: HTML7007: One or more blob URLs were revoked by closing the blob for which they were create ...

Unleashing the power of XPath and wildcards in AJAX

Can anyone explain why the variable objProperties, which contains an xpath with a wildcard, is coming up empty in this scenario? function getXMLServerObject (httpType, cmd, isAsync) { var object = new Array(); $.ajax({ type: httpType, ...

The performance of the React create app proxy agent in the package.json file seems to be sluggish,

In our react application (created as create-react-app), we have a proxy defined in the `package.json`. This proxy is used between the front-end (webpack) and back-end (express) during development, as outlined here. The section of the `package.json` where t ...

Troubleshooting await and async functions in Express.js applications

How can I create an array like the one shown below? [{ "item":"item1", "subitem":[{"subitem1","subitem2"}] },{ "item":"item2", "subitem":[{"subitem3","subitem4&q ...

Using React-Router-Config to dynamically set the page title

I am seeking advice on how to dynamically set page titles using the configuration file in conjunction with react-router-config. Should I use props or Helmet for this purpose? routes.js const routes = [ { title: 'Home', path: ...

Problem detected in id modification

My JavaScript function is triggered with an onChange event, which works fine when there's only one. <input class="form-control" type="text" onchange="opert(<?php echo $fetch["id_prod"] ?>,1)" id="name" value="<?php echo $fetch["name_prod" ...

The font in my Next.js / Tailwind CSS project starts off bold, but unexpectedly switches back to its original style

I recently integrated the Raleway font into my minimalist Next.js application with Tailwind CSS. I downloaded the font family in .ttf format and converted it to .woff2, but I'm having trouble changing the font weight using custom classes like font-bol ...

What could be causing the issue of the view not showing up in AngularJS?

I've been trying to use AngularJS modules to display a view, but for some reason my page isn't showing up. Can anyone help me figure out what's going on? You can check out my code at the following link: <!DOCTYPE html> <html> & ...

The handler for errors in DRW consistently generates the message "Error" instead of providing specific information about the issue at hand

FiltersManager.getAllServices({ callback : updateServiceFilter, errorHandler : function(message) { alert(message); } }); Although I throw an exception when an error occurs in th ...

How to combine two fetch calls in Nuxt3?

I have been attempting to chain two fetch calls in Nuxt3, where the second call is dependent on the result of the first one and I need to use the resulting "variable" in a Vue component. My current approach is: <script setup> const url = "myurl ...

How can we trigger parent functions to update props?

I'm currently facing a challenge when it comes to passing data down in React and Vue frameworks. In my Vue project, I've adopted a particular approach and I'm wondering if it's the right way to handle this. At the moment, the parent co ...

"Navigate back to a previous page in Vue Router without having to

I am currently exploring the option of creating a back button in my Vue.js application using vue-router that mimics the behavior of the browser's native back button. The challenge I'm facing is that when using history mode for the router and tryi ...