-1

I'm trying to use window.location.pathname and injecting innerHTML to generate the file paths for an image so all I need to do is type fileName.png in a div in the html body and have the javascript generate the file path behind it so that it displays the image in the rendered website. This is for images that aren't stored in the same folder as the working file. I've had mild success but it only works for one image per page which isn't very helpful.

I've gotten this code to work for one image per page:

<div class="picName">pic.png</div><div id=<"shortcut"></div>`

<script>
  var relativePath = window.location.pathname;
  var picName = document.getElementById('matts-shortcut').previousElementSibling.innerHTML;
  document.getElementById("matts-shortcut").innerHTML =
    '<src=\'/images' + relativePath + '/' + picName + '\'>';

</script>
Matt
  • 3
  • 2
  • can you show the code you tried for getting multiple to load? – Smern Dec 03 '18 at 17:41
  • You do know that you can only have a maximum of one element per page with any given `id` value? `id` must be unique. `document.getElementById(idVal)` will always return only the first element with the id `idVal`. – connexo Dec 03 '18 at 17:41
  • @connexo thats a helpful starting point; I'm brand new to this. I did try using a class and having getElementsByClassName but that doesn't work. – Matt Dec 03 '18 at 17:57
  • Where are the `` elements in your posted code? Should all `` elements be updated, or is it conditional and dependent on something? – David Thomas Dec 03 '18 at 18:04

2 Answers2

1

The solution below pulls images names from with Divs using .querySelectorAll() which returns a DOM NodeList. The NodeList is useful because it has a forEach() method that can be used to loop over each item is the list. Loop over each list item using it's textContent property as the image name. Then you'll need to create a new image element for each image. To do that you can do something similar to this.

let relativePath = "https://dummyimage.com"; // replace the url with path name (maybe window.location.path)
// create a reference to the input list
// querySelectorAll return a NodeList
let inputNameList = document.querySelectorAll('.image-name');
// Loop through each image name and append it to the DOM
// the inputNameList (NodeList) has a "forEach" method for doing this
inputNameList.forEach((image) => {
  let picName = image.textContent;
  // Create a new image element
  let imgEl = document.createElement('img');
  // Set the src attribute of the image element to the constructed URL
  // the name of the picture will be the div text content
  // This is done with a template literal that you can learn about here:
  // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
  imgEl.src = `${relativePath}/${image.textContent}`;
  // Now we have a real image element, but we need to place it into the DOM so it shows up
  // Clear the image name
  image.textContent = "";
  // Place the image in the Div
  image.appendChild(imgEl);
});
<div class="image-name">300.png</div>
<div class="image-name">200.png</div>
<div class="image-name">100.png</div>
<div class="image-name">400.png</div>

EDIT: In response to Ismael's criticism, I've edited the code slightly and commented every line so you can learn from this answer. There are two hyperlinks referenced in the code to help you think about coding in a modern way and so you can interpret modern code you read more easily.

About:

Edit 2: With further clarification, the answer has been amended to pull the image file names from Div elements already in the DOM.

Randy Casburn
  • 13,840
  • 1
  • 16
  • 31
  • This is so overcomplicated, specially to someone who's struggling with basic concepts. I understand the use of ES6, but why overcomplicate? Why use `document.querySelector('#add')` when `document.getElementById('add')` does the same but faster? Why introduce template strings and why do you run `document.querySelector` twice inside the event handler? I know ES6 is the present, but you are teaching someone. Keep it simple. – Ismael Miguel Dec 03 '18 at 18:14
  • @IsmaelMiguel - You are more than welcome to create your own answer. – Randy Casburn Dec 03 '18 at 19:05
  • @RandyCasburn Thanks Randy I really appreciate your answer, especially as I am just getting started with JS. I'll update my question to be a little bit more clear on what I'm trying to do. Essentially I want to be able to write
    filename.png
    in the html body and have the rendered website show the filename.png image so I don't have to write long file paths every time. Your solution works extremely well when I enter filename.png on the rendered website; however, I'm trying to enter it in the html body.
    – Matt Dec 03 '18 at 19:31
  • @Matt Use the `` element. Or use an `` with a `data-src` attribute. – Ismael Miguel Dec 03 '18 at 19:50
  • @Matt - The answer has been edited and reflects your original intent. Glad to be of help to you. Please note, to make this more realistic I added references to real images. You can still use your original intent of using the location.pathname property. – Randy Casburn Dec 03 '18 at 20:12
  • @RandyCasburn If you get a chance, one issue I noticed with this code is that the images are appended to the bottom of the page rather than where the
    – Matt Dec 03 '18 at 23:05
  • Do you want the image name (300.png) replaced with the image or the image along with the name? (assuming first option). – Randy Casburn Dec 03 '18 at 23:50
  • @RandyCasburn the first option would be the best. – Matt Dec 03 '18 at 23:51
  • Edited to reflect your comment. – Randy Casburn Dec 03 '18 at 23:53
0

Let ID equal your element's id

Call on: document.getElementById(ID).src = "image_src" When you want to change images, like an onclick action or as part of a function.