<div class="container"></div>
const run = () => {
const words =['King', 'Queen', 'Sword', 'King', 'Armor', 'King'];
const $container = document.querySelector(".container");
const getIndexes = (arr, target) => {
return arr.reduce((acc, word, i) => {
if(target === word) {
acc.push({
name: word,
index: i
})
} else {
acc.push({name: word});
}
return acc
}, [])
}
const insertHTML = (list) => {
list.forEach((item) => {
if(item.index !== undefined) {
var template = `<div data-index="${item.index}">${item.name}</div>`;
} else {
var template = `<div data-index="">${item.name}</div>`
}
$container.insertAdjacentHTML('beforeend', template)
})
}
insertHTML(getIndexes(words, "King"))
$container.addEventListener('mouseover', (e) => {
const index = e.target.getAttribute('data-index');
if(index) {
console.log(index)
}
})
}
run()