1

I have multiple buttons with the same class on my page, now when I try to call a method on the click event of the button, that method executes for all of the buttons because they have the same class.

The buttons on my page are dynamically created so I cant give different class to each button.

I am looking for a way to only execute some particular method on the click of the first element with the given class.

1

2 Answers 2

2

By using Jquery's .first() function, you can get the first element and then only bind the click event to it.

$(".sameClass").first().on("click", function() { console.log("clicked"); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="sameClass">Button 1</button>
<button class="sameClass">Button 2</button>
<button class="sameClass">Button 3</button>

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the help
Hm, very elegant way
2

Here it is:

$("button").each(function(i, item) {
  if(i === 0) {
    $(item).on("click", function() {
      console.log('works only for the first button');
    })
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class"test-class">btn 1</button>
<button class"test-class">btn 2</button>
<button class"test-class">btn 3</button>
<button class"test-class">btn 4</button>
<button class"test-class">btn 5</button>

I'm looping through all buttons and adding event listener only for the first of them.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.