jQuery User
jQuery User

Reputation: 1

Apply styling created with jQuery to newly created elements

I'm trying to figure out a way to apply existing jQuery-created styling to elements that are created. IE, if I style my elements as such:

$('a.something').css('background-color', 'black');

I want that styling to apply if I were to create another a.something via

$('#blah').append('<a href="#" class="something">stuff</a>');

I looked at the .live() function but it didn't seem to do exactly what I wanted.

Any help would be greatly appreciated.

Upvotes: 0

Views: 285

Answers (4)

Jeremy Battle
Jeremy Battle

Reputation: 1638

If you want all links with the class of "something" to have a black background you should specify that in your CSS not in your jQuery. Moving this to your class and using

$('<a href="#">stuff</a>').addClass("something").appendTo('#blah');

is the more obvious solution to me.

Upvotes: 0

Josh Bedo
Josh Bedo

Reputation: 3462

Are you looking for something like addClass() ? ex: $(".class").addClass("newclass");

Upvotes: 0

Daniel Ahrnsbrak
Daniel Ahrnsbrak

Reputation: 1077

I think David Thomas has the right answer, but if you really wanted to do what you're saying, you could just put that $('a.something').css('background-color', 'black'); into a function and call it after the append.

Upvotes: 0

David Thomas
David Thomas

Reputation: 253318

The easiest option is to simply use jQuery to apply an already-existing class name to an object, rather than using the .css() method; that way any newly created elements, given that class-name, will automatically be assigned that styling.

Upvotes: 1

Related Questions