Skip to content
Advertisement

How to rewrite code without the .video element in it? [closed]

How would that be done here? https://jsfiddle.net/bqfv5j06/

Those were the instructions I was given.

Currently, I am telling JavaScript to go find it every time a button is clicked. This is the equivalent of Googling for the person’s phone number everyday. It is a waste of time and system resources.

document.querySelectorAll('button.cover').forEach(function(button) {
  button.addEventListener('click', function (event) {
    document.querySelector('.video').dataset.id = event.target.dataset.id;
  });
});

How exactly would this be done?

Me: If I understand you correctly, you are wanting me to rewrite that code without the .video element included in it?

Do I have that correct?

And the answer I got back was, “Yes”

Advertisement

Answer

Your instructor wants you to cache the result of the call once, and then use that cache instead of searching the DOM every time.

const myVideo = document.querySelector('.video');

document.querySelectorAll('button.cover').forEach(function(button) {
  button.addEventListener('click', function (event) {
    myVideo.dataset.id = event.target.dataset.id;
  });
});

If you want to use this with a “standard for loop”, you can do this:

const myVideo = document.querySelector('.video');

const buttons = document.querySelectorAll('button.cover');

for (let i = 0; i < buttons.length; i++) {
  buttons[i].addEventListener('click', function (event) {
    myVideo.dataset.id = event.target.dataset.id;
  });
}
// or
for (const button of buttons) {
  button.addEventListener('click', function (event) {
    myVideo.dataset.id = event.target.dataset.id;
  });
}
Advertisement