There is already question about getting a dom element by using an attribute value. But mine is different because my attribute value is not known beforehand.
<div class='gameBoard'> <div class="grid" index='0'></div> <div class="grid" index='1'></div> <div class="grid" index='2'></div> <div class="grid" index='3'></div> <!-- Goes up to 100 div / 99 index values --> </div> I have a div gameboard representing a dom element which contains 100 div, each with the index values from 0 to 99. Below im looping through all the divs and when the mouse hovers over a div, than I gets its index ( data-attribute ). ( if the direction is on the x-axis, then I do this )
const one = el; const onei = el.getAttribute('index'); const two = el.nextElementSibling; const twoi = two.getAttribute('index'); But when the direction is on the y-axis, I don't need the next div element but the one below. For ex: if index is 0, I need 0 + 10 = 10, so i need the div with index 10. I tried the code below but it is not working cuz the value is retrieved dynamically, I tried using string interpolation and it doesn't work. So please help !!!
const grids = document.querySelectorAll('.grid'); el.addEventListener('mouseover', (e) => { if (foo === 'destroyer' || foo === 'submarine') { if (currentDirection === 'Y') { const one = el; const onei = Number(el.getAttribute('index')); const twoi = onei + 10; const two = document.querySelector("[index='twoi']"); console.log(two, twoi); } } });
const two = document.querySelector(`[index='${twoi}']`);- Notice the backticks.