PureJavaScript: forEach Selector
by Farzad Cyrus
HTML
<section class="class-1">Section 1</section>
<section class="class-2">Section 2</section>
<section class="class-3">Section 3</section>
CSS
html, body {
margin: 0;
padding: 0;
font-size: 14px;
font-family: sans-serif;
}
section {
height: 80px;
width: auto;
background: #48e;
color: #fff;
margin: 16px;
line-height: 80px;
border-radius: 2px;
text-align: center;
display: block;
}
JavaScript
var selector = document.querySelectorAll('section');
Array.prototype.forEach.call(selector, function(el, i) {
el.addEventListener('click', function() {
alert('You clicked on ' + this.attributes.class.value);
});
});