Multiple like and dislike buttons are not working in a webpage?

I am having a page in which I am showing the like and dislike button in a particular div , it is working quite good for one like and dislike button but not for ,multiples.
Here is the code :

<script>var btn1 = document.querySelector('.green');
var btn2 = document.querySelector('.red');
btn1.addEventListener('click', function() {
if (btn2.classList.contains('red1')) {
btn2.classList.remove('red1');
}
this.classList.toggle('green1');
});
btn2.addEventListener('click', function() {
if (btn1.classList.contains('green1')) {
btn1.classList.remove('green1');
}
this.classList.toggle('red1');
});
</script>
<style>
.btn{
cursor: pointer;
outline: 0;
color: #AAA;
padding:5px 10px;margin-bottom:0;background-color:rgb(240, 240, 240);
}
.btn i{font-size:16px;}
.btn:focus {background:transparent;}
.btn.green1{color: green;}
.green1{color: green;}
.btn.red1{ color: red;}
</style>
<div>
<button class="btn green"><i class="fa fa-thumbs-up fa-lg" aria-hidden="true"></i></button>
<button class="btn red"><i class="fa fa-thumbs-down fa-lg" aria-hidden="true"></i></button>
</div>
<div>
<button class="btn green"><i class="fa fa-thumbs-up fa-lg" aria-hidden="true"></i></button>
<button class="btn red"><i class="fa fa-thumbs-down fa-lg" aria-hidden="true"></i></button>
</div>

Hi @Shobha, can you elaborate more on “not working for multiple buttons” ? Also, is it possible to include a link to your project so we can see the whole picture of your code?

I am running the project in local host

This is my fiddle:
https://jsfiddle.net/shobha_patwal/j4x9La81/4/

You have two buttons with class .green so when you querySelector(".green"), only the first button is selected.

A solution will be using querySelectorAll which gives you a NodeList of both buttons with class “green”.

Here’s my example: https://jsfiddle.net/mingy/bq2xmprs/3/
Open up your console to see what’s selected. Hope this helps!

In second div it is not selecting dislike button color.

My bad, I didn’t login and my code is not saved properly. I have changed the link, please try again.

Thank you for your help, its working now :grinning:

No it is creating some error…

You are welcome! What’s the error?

This is my fiddle:
https://jsfiddle.net/shobha_patwal/0jy9pkga/

Dislike button is not working in second row… on clicking one button second button is disabling removing the class

Did you select one dislike button or both? (hint: querySelector)

I am selecting both buttons from each row

You did for btns1! You used a querySelectorAll, that’s why when you console out btns1, you will see two elements are selected. However, look closer to what you are selecting for you dislike buttons(with class name “red”), are you sure you have selected all dislike buttons?

@mingyco this is my fiddle