for each in javascript- arrow or lamda funtion in java script
<!DOCTYPE html>
<html lang="en">
<head>
<title>Colors</title>
</head>
<body>
<h1 id="hello">Rajan</h1>
<button data-color="red">Red</button>
<button data-color="blue">Blue</button>
<button data-color="brown">Yello</button>
<button data-color="white">rainbow</button>
</body>
</html>
<script>
document.addEventListener('DOMContentLoaded', function() {
document.querySelectorAll('button').forEach(function(button) {
button.onclick = function() {
document.querySelector("#hello").style.color = button.dataset.color;
}
});
});
</script>
@* same above can be achieved with arrow funtion(lamda or anonymus funtion in other language)*@
@*document.addEventListener('DOMContentLoaded', () => {
document.querySelectorAll('button').forEach(button => {
button.onclick = () => {
document.querySelector("#hello").style.color = button.dataset.color;
}
});
});*@
@*
We can also have named functions that use arrows, as in this rewriting of the count function:
count = () => {
counter++;
document.querySelector('h1').innerHTML = counter;
if (counter % 10 === 0) {
alert(`Count is now ${counter}`)
}
}*@
Comments
Post a Comment