17

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?

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Omar Abid
  • 15,753
  • 28
  • 77
  • 108

3 Answers3

24

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");
    
Andy E
  • 338,112
  • 86
  • 474
  • 445
  • I was using a stylesheet and what I wanted to do is to get rid of it (less files) and use CSS since its inline CSS. – Omar Abid Sep 15 '10 at 11:59
  • 4
    @Omar inline CSS is a very bad idea in general. There's nothing wrong with having one CSS file with your styles in. In fact it's beneficial because users will download it once and it should be cached on subsequent page views. Although I should say, inline CSS is fine when you need to do it dynamically, e.g. you don't know the required width/height of an element ahead of time. – DisgruntledGoat Sep 15 '10 at 12:06
  • @OmarAbid , you can just specify classes inside HTML which may or may not have CSS definitions in your CSS file. Jquery does not work based on the definitions of those classes. – KBN Apr 29 '12 at 14:55
1

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

Dev Matee
  • 5,525
  • 2
  • 27
  • 33
  • sorry, I just tried that on a combobox (select>option), so this didn't work, but surely because "option" have no way to CSS the internal nested elements... so should be normal – serge Aug 09 '19 at 08:35
  • This works only on present elements when JQ scans DOM. All new elements WILL NOT be scanned, thus, your solution does not work. – Alex Khimich Jan 22 '21 at 11:26
0
$('head').append('
< style >
.folder { background: url(../icons/Folder_icons/g/f.png) no-repeat left top;} < / style >');
Rizier123
  • 58,877
  • 16
  • 101
  • 156