1

I am trying to enable click function on every link with the same class name and unique id. But the problem is click function is working only on first link. The number of links are unknown they can be 1 , 2 , 3 or any...

so Buy getting the number of links with the same class name trying to make a loop for every click function..Can anyone please help me!

the code I am trying is

<a class="divclasss" id="clicki25" >
    <i class="fa fa-envelope"></i>
</a>
<a class="divclasss" id="clicki26" >
    <i class="fa fa-envelope"></i>
</a>

<a class="divclasss" id="clicki27" >
    <i class="fa fa-envelope"></i>
</a>

Jquery code I am using is

  alert($('.divclasss').attr("id")); 


for (var i=0; i<$('.divclasss').length; i++) {
$("#id").click(function(){  
/// 
}); 
}   

1.) How can I know the total number of links? 2.) For every div with unique id enabling click function.

user3739733
  • 181
  • 1
  • 3
  • 14

4 Answers4

2

Why don't you do this, instead of binding functions by using id. Just notice, you have a common class divclasss for each elements.

$('.divclasss').click(function(){
  console.log(this.id); //clicki25 , clicki26 based on the clicking element
});
Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130
  • working fine, thanks a lot.. I had done a lot of coding based on my above concept. But sir you made it so easy and almost solve my problem. But still i will ask some question related to this later..Can I? – user3739733 Jun 25 '14 at 10:41
  • @user3739733 Asking question in this post wont help the future readers who is facing same problem as like you, so ask that question as a separate one and link me to that question. By the way, glad to help..! If you feel anyone of the answers present here satisfied your need, just accept it. :) and it is not a compulsion.. :) – Rajaprabhu Aravindasamy Jun 25 '14 at 10:43
  • One little thing I have asked here [link](http://stackoverflow.com/questions/24408186/how-to-get-the-value-of-this-id-in-string) – user3739733 Jun 25 '14 at 12:06
1

Since it has the same class name,you don't have to loop like that, just use

$('.divclasss').click(function(){
   alert($(this).attr("id");
  });

or you can use jquery attribute starts with selector

$("[id^=clicki]").click(function(){
  alert($(this).attr("id");
});
Anoop Joshi P
  • 25,373
  • 8
  • 32
  • 53
0

Try this using common class

1) for length

var totalClass= $('.divclasss').length; 

2) click event

  $('.divclasss').click(function(){


  });
Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130
Balachandran
  • 9,567
  • 1
  • 16
  • 26
0

You don't have to loop through all divs, just bind click event using class selector :

$('.divclasss').click(function(){
  //do click task here
});
Bhushan Kawadkar
  • 28,279
  • 5
  • 35
  • 57