Omar Abid
Omar Abid

Reputation: 15976

jQuery CSS() for dynamically created elements

I'm using jQuery CSS function to style some elements

$element.css(style);

This works, but a part of the elements are created dynamically after the page load. This should be

$element.live ('created',function() {
$(this).css(style);
});

I'm stuck on the created event. Any ideas?

Upvotes: 17

Views: 28969

Answers (3)

Dev Matee
Dev Matee

Reputation: 5939

Best Idea is to Define CSS classes. And then Remove and add classes from Dynamic elements as per need

$(element).addClass("className");
$(element).removeClass("className");

Example: JS Fiddle

Upvotes: 1

user2935404
user2935404

Reputation: 1

$('head').append('
< style >
.folder { background: url(../icons/Folder_icons/g/f.png) no-repeat left top;} < / style >');

Upvotes: 0

Andy E
Andy E

Reputation: 344575

There's no event for elements created (not universally available, anyway). You could

  • Add the rules to a stylesheet so that they are automatically applied to the newly created elements
  • Chain the css() method when you create your elements:

    $('<img id="createdImage" src="some.jpg"/>')
        .appendTo(document.body)
        .css(style);
    
  • Create a new stylesheet dynamically:

    $("<style>").text("#myNewEl { width:20px; height:30px; }").appendTo("head");
    

Upvotes: 24

Related Questions