Javascript Question

Split image src attribute with plain vanilla JavaScript and no Regex

SOLVED!



Many thanks to Michael Camden for providing me another set of eyes and finding my mistake. After making the correction he suggested, the code works perfectly.

For anyone else looking for a plain JavaScript way to get all the image names from a webpage without all the file path location info, here is the script I wrote that works like a charm:

var links = document.getElementsByTagName('img');

for (var i=0; i<links.length; ++i) {

console.log(links[i].src);

var partsArr = links[i].src.split('/');
console.log(partsArr);

var imageName = partsArr[partsArr.length -1];
console.log(imageName);


}





The Issue



I'm trying to figure out how to split a src element with plain vanilla Javascript for an
<img>
tag. I think my code is pretty solid but Chrome developer console keeps giving me "someFunction is not a function errors".

My Code



Here is my current code:

var links = document.getElementsByTagName('img');

for (var i=0; i<links.length; ++i) {

console.log(links[i].src);

var partsArr = links[i].toString().split('/');
console.log(partsArr);


}


It runs, but the output I get for partsArr is:

["[object HTMLImageElement]"]


I was expecting something more like:

["file:","pathpart1", "pathpart2", ... "filename.ext"]


NOTE: I have to do this with plain JavaScript because jQuery isn't available. Also, it's a page on localhost, and I'm coding in Chrome developer tools console, if that makes a difference.

What I've Tried Already



I have already searched for a duplicate and have not found one that exactly answers what I am asking. Here are the posts I referenced before submitting this question:

Javascript: Split and variable issues

Split a image tag on html string

Getting image src name javascript

How to split and assign 2 words?

What is causing the following error: "string.split is not a function" in javascript?


My Questions




  1. How do I parse the image file name from an
    <img>
    tag src attribute, using just plain vanilla JavaScript, and no regexes?

  2. What am I doing wrong in my current code?



I hope this makes sense.

Any help is appreciated.

Answer

It looks like this part is wrong,

var partsArr = links[i].toString().split('/');

Instead of executing 'toString' on the element object, you should just access the .src property from the element. So,

var partsArr = links[i].src.split('/');
Comments