Class created during document loaded

Hi, I have an element (‘a’) which is no class and no Id, dynamically i created the class during the document loaded.

this is how i add class on a element.


$('.mainclass').find('a').eq(1).addClass('firstclass');


I putted an alert so that i will know that i click the firstclass.


$(function(){
  $('firstclass').click(function(){
    alert("this is firstclass");
});

});


unfortunately it will not alert.but i inspect in the firebug the firstclass is in there…I don’t know why it did not alert.

please enlighten my mind on this,.

Thank you in advance.

Because there is an error in your JS.

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

should be:

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

Note the missing dot before the class name.

yup,i got wrong typo for that,but here in my code

$(‘.firstclass’).click(function(){

still does not work.

Hi pullo, can i ask something what is the event.preventDefault() ? what is the purpose for this?

Hi there,

I think that your problem is that you are not stopping the browser from following the link and that is why you are not seeing an alert.
This is what event.preventDefault() or return false are for.
See this: http://stackoverflow.com/questions/1357118/event-preventdefault-vs-return-false

Other than that, this will work as expected:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>jQuery addClass</title>
    <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
  </head>

  <body>
    <div class="mainclass">
      <a href="www.sitepoint.com">Sitepoint</a><br />
      <a href="www.google.com">Google</a>
    </div>
    <script>
      $(document).ready(function() {
        $('.mainclass').find('a').eq(1).addClass('firstclass');
        $('.firstclass').click(function(){
          alert("this is firstclass");
          return false;
        });
      });
    </script>
  </body>
</html>

Okay,it show now the alert.THank you :slight_smile: