I created a set of buttons when clicked a style is added. I wanted to make it more interesting in that upon clicking another button, the style of the previously clicked button should be removed. Unfortunately, I've no idea how to make that happen. I know it's such a basic question but it's already been a day! Can you guys plz help me with that and end my torture?
Here's the code:
//HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Starter</title>
<!-- font-awesome -->
<link
rel="stylesheet"
href="stylesheet.css"
/>
</head>
<body>
<button>hello</button>
<button>hello</button>
<button>hello</button>
<button>hello</button>
<script src="plzwork.js"></script>
</body>
</html>
//JS
var button = document.querySelectorAll('button')
button.forEach(function(btn){
btn.addEventListener('click', function(){
btn.style.color = "red";
})
});
CodePudding user response:
Try this...
//JS
var button = document.querySelectorAll('button')
for(var i =0; i< button.length; i ){
button[i].onclick = function(){
button.forEach(function(btn){
btn.style = '';
});
this.style.color = 'red';
}
}