0

I try to iterate through querySelectorAll() and get their data- values (I feel like I didn't explained it well so I hope that the code below will be more helpful for me to explain what I mean):

<input type="text" id="data-element" placeholder="Insert value here" readonly />
<a href="javascript:" data-element data-element-value="Value 1">Click me to set value</a>
<a href="javascript:" data-element data-element-value="Value 2">Click me to change the current value</a>

window.addEventListener('load', function(){
    document.querySelector('body').onclick = function() {
        if(document.getElementById('data-element') !== null) {
            var output  = document.getElementById('data-element');
            var anchors = document.querySelectorAll('a[data-element]');
            for(var i = 0; i < anchors.length; i++) {
                anchors[i].onclick = function() {
                    output.value = anchors[i].getAttribute('data-element-value');
                }
            }
        }
    }
});

I need to output the value of each [data-element-value] where [data-element] is not null (or: exists) into #data-element (or: id="data-element")

as you can see, it doesn't work... how can I solve this?

  • 1
    In your case, the really easy fix is to change `output.value = anchors[i].getAttribute(...);` to `output.value = this.getAttribute(...);` The linked question's answers explain why it wasn't working (the value of `i` was not what you thought it was as of when the click occurred). – T.J. Crowder Oct 16 '16 at 10:15
  • @T.J.Crowder Thank you very much! :) –  Oct 16 '16 at 17:41

0 Answers0