3

I have created some dynamic divs under 'parent' div and set fetched data from json in these dynamic divs. now I want to use a onclick function to get the index value of these dynamic divs which will be clicked. but don't know how to do.

fetch('https://restcountries.com/v3.1/all')
    .then(response => response.json())
    .then(json => display(json));

function display(datas) {
    let parent = document.getElementById("parent");
    datas.forEach(data => {
        let div = document.createElement('div');
        div.classList.add('list');

        div.innerHTML = ` 

        <li>country Name: ${data.name.common}</li>
        <li>country Continents: ${data.continents[0]}</li>
        <li>Total arae: ${data.area}</li>
        <img src="${data.flags.png}" alt="" style="display: none">`

        parent.appendChild(div);

    })
}
<body>
    <div id="parent">
        <img src="" alt="">
    </div>
    <script src="country.js"></script>
</body>
Christian
  • 4,902
  • 4
  • 24
  • 42
Nafiz Imtiaz
  • 63
  • 1
  • 5
  • I don't fully understand what you're asking, but the `forEach` function takes the item index [as a second argument](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach#syntax) if that helps. – ray Sep 06 '22 at 22:44

2 Answers2

1

You can get the index of an html element relative to a parent by getting a collection of the elements, convert it to an array, and then get the index in the usual way with the native array indexOf method:

function getIndex(div) {
    const parent = document.getElementById("parent");
    const collection = Array.from(parent.querySelectorAll(".list"));
    const index = collection.indexOf(div);
    return index;
}

You can use event delegation to automatically assign a click handler to all .list elements as they are created

const parent = document.getElementById("parent");
parent.addEventListener('click', function (event) {
    const item = event.target;
    if (item.matches(".list")) {
        console.log("index: ", getIndex(item));
    }
});
fetch(//...

example:

const parent = document.getElementById("parent");

function getIndex(div) {
    const collection = Array.from(parent.querySelectorAll(".list"));
    const index = collection.indexOf(div);
    return index;
}

parent.addEventListener('click', function (event) {
    const item = event.target;
    if (item.matches(".list")) {
        console.log("index: ", getIndex(item));
    }
});

parent.innerHTML = `
<div class="list">A</div>
<div class="list">B</div>
<div class="list">C</div>
<div class="list">D</div>
`;
<div id="parent"></div>
chiliNUT
  • 18,989
  • 14
  • 66
  • 106
0

You can achieve index using second argument of forEach iteration function

arr.forEach(function callback(currentValue, index, array) {
    //your iterator
}[, thisArg]);

So, part of your code will look like this:

datas.forEach((data, index) => {