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?

2
  • How are the elements being created? Can you not just use a CSS class? Commented Sep 15, 2010 at 11:52
  • I was using and wanted to move to a class less solution. Commented Sep 15, 2010 at 12:00

3 Answers 3

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");
    
Sign up to request clarification or add additional context in comments.

3 Comments

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 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.
@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.
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

2 Comments

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
This works only on present elements when JQ scans DOM. All new elements WILL NOT be scanned, thus, your solution does not work.
0
$('head').append('
< style >
.folder { background: url(../icons/Folder_icons/g/f.png) no-repeat left top;} < / style >');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.