views:

44

answers:

3

I am dynamically adding a class to my code using Jquery's .attr('class', 'show'). But when I use .each() function like this:

$('.show a').each(function() {
    alert(0);
});

it doesen't work.

I works when I added the 'show' class manually.

How can I do this dynamically?

+3  A: 

Use "addClass" instead of trying to set the class via "attr()".

Pointy
+1  A: 

I assume you mean that you're adding a class to an existing element. If so it may work better if you used:

$('.myElement').addClass('show');

If you need to add an element to the dom, that's a completely different matter.

EDIT:

To address the new info you gave, there are two things to change:

First, use addClass:

$('#existing div:first').show().addClass('show');

Second, you forgot the . before 'show' for your each. It should be ('.show a'):

            $('.show a').each(function() {
                alert(0);
            });
patrick dw
A: 

I have existing element div.

$('#somewhere').click(function() {                  

                $('#existing div:first').show().attr('class', 'show');

                $('show a').each(function() {
                    alert(0);
                });
});     

My code: <div id="existing"> <div> <a href="#">a1</a> <a href="#">a2</a </div> <div> <a href="#">b1</a> <a href="#">b2</a> </div>

I tried .addClass and .attr...

kicaj
You're new here, so just want to let you know that if you wish to clarify your question, it is better to edit the original question, or add a comment like this to one of the answers. I've edited my answer to address the problem.
patrick dw