Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery CSS() for dynamically created elements

Tags:

jquery

css

live

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?

like image 560
Omar Abid Avatar asked Sep 15 '10 11:09

Omar Abid


People also ask

How do I apply CSS to dynamic content?

The better way is to add css classes which you want to add and then use addClass to add css dynamically.

Which function in jQuery can be used to change the style of an element dynamically?

The css() method is used to change style property of the selected element.

How do you select a dynamic class in CSS?

Use another CSS class selector *="class" (equivalent to CSS attribute selector) which select all elements whose class contains at least one substring "box-".

How do you apply dynamic class to an element?

In this article, we will see how to dynamically create a CSS class and apply to the element dynamically using JavaScript. To do that, first we create a class and assign it to HTML elements on which we want to apply CSS property. We can use className and classList property in JavaScript.


2 Answers

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");
    
like image 157
Andy E Avatar answered Oct 23 '22 22:10

Andy E


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

like image 32
Matee Gojra Avatar answered Oct 23 '22 22:10

Matee Gojra