How would I display individual elements of an array on an individual click?

Viewed 82

How would I be able to display the individual element that's stored in an array onclick? I have divs with the same class name that I can click on and each div has its own data-id attribute with a value consistent with what's in the array below (the numbers in the array are assumed).

With my code below, it always displays 1 no matter which div I click. i.e, if I click on the 2nd, 3rd or 4th div, 1 always shows up.

How can I make it so that whenever I click on the first div, then 1 appears. If I click on the second div, then 2 appears, and so on. I also want to be able to switch between clicking on them and having it display the correct number all the time.

I've been stuck on this for so long and I've hit a wall, I'd greatly appreciate any help :).

let arr = [1,2,3,4];
let campaignId = $('.cpi-wall-item').attr('data-id');

for(let i = 0; i < arr.length; i++) {
        if(arr[i] === campaignId) {
            console.log(campaignId)
        }
    }
1 Answers

Without seeing your full code, including your on-click or a working example it is hard to determine what is going wrong here, however, there are a few ways you can do what you are doing more easily, depending on your actual use case:

1: using arr.indexOf()

let arr = [1,2,3,4];
let campaignId = $('.cpi-wall-item').attr('data-id');
console.log(arr.indexOf(campaignId));

2: using an Object where the div you click holds the key in your array you are looking for:

let obj = {"1":1,"2":2,"3":3,"4":4};
    let campaignId = $('.cpi-wall-item').attr('data-id');
    console.log(obj["campaignId"]);

3: if you know that div 1 will have its correlating element in the first position you can simply add that as your data-id

let arr = [1,2,3,4];
    let campaignId = $('.cpi-wall-item').attr('data-id');
    console.log(arr[campaignId]);
Related