February 2018
Intermediate to advanced
298 pages
8h 22m
English
Just like you can get any element with querySelector, you can get a bunch of elements matching the criteria with querySelectorAll. You've seen how to work with NodeList in the getElementsByClass method. Try to understand the code as follows:
<div data-attr="red">Make me red!</div><div data-attr="blue">Make me blue!</div><script>[...document.querySelectorAll('div[data-attr]')].map(div => { div.style.color = div.attributes['data-attr'].value;});</script>
First, we're converting NodeList to Array using destructuring. Then we're mapping over the array and changing the style of each <div> according to the value of its data-attr.
Read now
Unlock full access