DavidTonarini
DavidTonarini

Reputation: 951

How to add css on elements created through ajax (jquery)?

I have a cart that’s graphically styled with a CSS file. However, when I update the cart through jQuery and AJAX, the reloaded version is not styled.

Is there any jQuery function to apply already loaded styles to a dynamically generated element?

I know I could use .css() function to add the style manually, but I’d rather avoid that and be able to load the existing properties automatically, so that it doesn’t become messy if I make changes.

Thanks, kind regards.


Sorry guy, I guess I’m a bit confused or something. It does work by itself and the css is automatically recognized without any special code. I’m not sure why it failed before, I’ve rewritten the code so I can’t tell, but I guess there was somewhere an error while declaring the class.

Anyway: while using correctly classes in css and html this is not a problem and it just works.

Upvotes: 2

Views: 1078

Answers (2)

PolCPP
PolCPP

Reputation: 136

While adding classes could fix it. There's something odd.

You said that when you update it via javascript you lose the style. It doesn't make sense.

The only way you could destroy the styling would be, altering the dom (so the new cart is different to the old according to the rule that styles it) or the old cart was inline styled and you cleaned its styles.

If it's inline css you could save the inline style document.getElementById("cart").style.cssText and apply it to the new cart.

Upvotes: 2

OneChillDude
OneChillDude

Reputation: 8006

If you use classes in your css, you can use the .addClass method to add the classes you want. It is significantly less messy that declaring inline css.

Upvotes: 2

Related Questions