Home > Mobile >  Find a DOM Element using an attribute-value which is acquired dynamically?
Find a DOM Element using an attribute-value which is acquired dynamically?

Time:03-21

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  index='0'></div>
   <div  index='1'></div>
   <div  index='2'></div>
   <div  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);
        }
    }
});

CodePudding user response:

The string concatenation inside querySelector is wrong

It should be working with this below code for that line

const two = document.querySelector(`[index="${twoi}"]`);

CodePudding user response:

Your issue is that of string interpolation. You're literally looking for an element that has the index twoi. Insteady, try interpolating the string with back ticks, e.g.

const two = document.querySelector(`[index='${twoi}]'`);

or just adding the twoi string to it:

const two = document.querySelector("[index="   twoi   "]");

  • Related