Home  >  Q&A  >  body text

Get data-value using variable value

There is a data-value in my php code that is used in multiple places, for example:

<a class="dropdown-item" data-value="<?= $i ?>"></a>
<a class="dropdown-item" data-value="<?= $k ?>"></a>

Now I need to use one of these values ​​in my script

getAttribute('data-value')

But I can't just use data-value because it will be related to everything I have, I just need to use this data-value="<?= $k ?> ;"

How to specify the value of this variable in the script?

P粉828463673P粉828463673185 days ago344

reply all(1)I'll reply

  • P粉860897943

    P粉8608979432024-03-22 11:38:09

    Since you want to get the data value of a specific element using the $k variable, your best option is to give that specific element an id and select it by id:

    HTML

    JS

    const elementWithK = document.getElementById('element_with_k');
    
    elementWithK.dataset.value // "the content of $k"

    If you want to select multiple elements, then you can add an extra class to those elements, query for all elements with the extra class, loop through them and get the value of each element.

    Hope this helps, cheers!

    reply
    0
  • Cancelreply