1

In JavaScript I want to load an image file from a different directory. My file structure is as such:

Project/js/script.js
Project/img/1.png

In script.js I want the following:

document.getElementById("image").src = "Project/img/1.png";

How do I make this work?

3
  • What is the path of your main HTML file? That is what establishes the base path by which relative paths are evaluated. Commented Nov 10, 2014 at 22:35
  • Project/index.html Commented Nov 10, 2014 at 22:36
  • Try document.getElementById("image").src = "/img/1.png"; Commented Nov 10, 2014 at 22:37

2 Answers 2

1

Your HTML file establishes the base path by which other relative paths are evaluated. So, if your HTML file path is "http://example.com/something/Project/index.html", then the Project directory is already the default location so you can access other things relative to the Project directory like this:

js/script.js
img/1.png

Any relative path that does not start with a domain or with / will have http://example.com/something/Project/ prepended to it.

Sign up to request clarification or add additional context in comments.

Comments

1

The browser doesn't ever know what root folder the files are in - it only knows what it sees from the URL. It seems like your project's root is in the Project folder, and everything lives under that. (like when you go to http://example.com/, your web daemon is configured to look in your 'Project' folder?)

so you should be able to do:

document.getElementById("image").src = "/img/1.png";

the first slash says "go to my root folder, whatever that is on the web server", and then the rest is just the remaining path.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.