querySelector
can return null
. So while you are checking button
, you aren't checking for iframe
. You will possibly get Assigning property src to undefined
or something like that.
classList
is one of the newer properties. If you see your code being used in older browsers, you should watch out. Check the compatibility table for support.
A practice used by jQuery and other libraries is to use sets. It's where you put results in an array and for each item, operate on it. If no items are on the set, no code executes.
// Use querySelectorAll to get elements. querySelectorAll returns a
// NodeList. To use array methods, we convert it to an array with
// slice.
const buttons = Array.prototype.slice.call(document.querySelectorAll('.js-brand-video--thumbnail'));
const iframes = Array.prototype.slice.call(document.querySelectorAll('.js-brand-video--iframe'));
// forEach runs the callback for each item in the array. If no items
// reside, no loop runs, therefore no code executes.
button.forEach(function(button){
button.addEventListener('click', function(){
button.classList.add('video-poster--hidden')
iframe.forEach(function(iframe){
iframe.getAttribute('data-src');
});
}, false)
});