'get data-value with variable value
I have a data-value
in my php code that is used in several places, for example:
<a class="dropdown-item" data-value="<?= $i ?>"></a>
<a class="dropdown-item" data-value="<?= $k ?>"></a>
And now I need to use one of these values in the script
getAttribute('data-value')
But I can’t just use data-value
, since it will be relevant to everything that I have, I only need to use this data-value="<?= $k ?>"
How can I specify a value with this variable in the script?
Solution 1:[1]
since you want to get the data-value of a specific element with the $k variable, your best bet is giving an id to that specific element and selecting it by id:
HTML
<a id="element_with_k" class="dropdown-item" data-value="<?= $k ?>"></a>
JS
const elementWithK = document.getElementById('element_with_k');
elementWithK.dataset.value // "the content of $k"
In case thete are multiple elements that you want to select then you add an extra class to those elements, query all the elements that have the extra class , loop through them and get each element's value.
Hope this helps, cheers!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | A. Pallis |