0

I have this feeling that I already tried everything and searched in several places for solutions but nothing works for me. I need to take out the updated mv value from addEventListener

HTML

<ul class="products" id="searchResult"> </ul>
<li multip="1.6"> scrambled eggs </li>
<li multip="1.2"> rice </li>

JS

const list = document.querySelector('ul'); 
var mv;
    list.addEventListener('click', e => {
            mv = e.target.getAttribute("multip");

    });

    console.log(mv);

So I understand I can't read the updated mv value because it is declared locally, however, is there is any way to reach it globally?

Usbv
  • 1
  • 2
    Does not make any sense, it will update the variable, but you would need to read it after it is select. Unclear what you are trying to do exactly. Problem with your example is you read the value as soon as the page renders, there is no sleep/wait so you can not sit there and wait for something to be selected. That is why you have the event listener where you can trigger something. – epascarello Jul 28 '21 at 18:55
  • 2
    Your update works well and the value will be accessible. But your function which reads your new value should run after your click otherwise what is the point. Check if that happens first. – Tushar Shahi Jul 28 '21 at 18:56
  • 1
    How can you expect `mv` to print *now* as the value which it will only get in some *future*? – trincot Jul 28 '21 at 18:58
  • https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron – epascarello Jul 28 '21 at 19:05
  • I see the problem. Thanks, guys. – Usbv Jul 28 '21 at 19:11

1 Answers1

-1

Use the same selector that you used to set up the listener in the first place:

document.querySelector('ul').setAttribute("multip", whatever you want);
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71