2

Have a litle problem here with multiple array in Javascript.

I define the array like this: var list = [];

In html I have <img class="Img" id="2" src="/test.png"/> My goal is to make a multiple array like this on "onload":

list[2][test.png]

Where 2 is the id tag, and the other is the image. In that way I later can do a loop and collect all photos belonging to list[2] or list[3] is that ID exist.

But my problem is, I can't get this to work. I tried this:

        var images = document.getElementsByClassName("Img");

     for(var i=images.length; i--;) {
        var PhotoId = images[i].getAttribute('id'),  // Id on the photo
            image = images[i].getAttribute('src');               // The images

     }

If I now in the loop this.list.push(image) it work like a charm, but that is one-dimensional.

How can I use this PhotoId as I explained above?

3 Answers 3

3

in single line u can also do it as, check if list[photoId] array already exists, if yes then push the image into it otherwise create an empty array.

list[photoId] ? list[photoId].push(image) : (list[photoId] = []).push(image);
Sign up to request clarification or add additional context in comments.

1 Comment

Fast and effective. Solved my problem. :)
1

Try this,

var images = document.getElementsByClassName("Img");

var arr=[];// array
for(var i=images.length; i--;) {
    var PhotoId = images[i].getAttribute('id'),    // Id on the photo
    image = images[i].getAttribute('src');               // The images
    arr[PhotoId]=image;
}
console.log(arr);

2 Comments

I like this reply, but I see a new problem. Say you have in HTML multiple img src tags with different IDs. They will not be added to the array, Example id 2,3,4. Only first id it seems
I got this error in console.log [undefined, undefined, "/avatar.png", undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, undefined, "/avatar.png"]
0

You can use

this.list[photoId] = []

then

this.list[photoId].push(image)

On another note id should be unique in DOM. If you want to group elements with certain property then use class attribute.

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.