7

I want to change the dimensions of a set of elements that are not created yet. They will be created by a JavaScript script that I don't have access to. JQuery's css() function would apply the changes only on existing items, while I want the code to work like if I had set CSS properties in a CSS file.

Can anyone help me do it?

Peter O.
33k14 gold badges86 silver badges97 bronze badges
asked Nov 10, 2012 at 21:12
5
  • Do those elements have something identifiable, like a class? If so, you could define rules directly in CSS. Commented Nov 10, 2012 at 21:13
  • What's the problem of setting these properties in CSS? Commented Nov 10, 2012 at 21:13
  • @pimvdb The CSS properties of the element must be set based on the user action. Commented Nov 10, 2012 at 21:17
  • @VisioN The elements I want to edit do have a class. Commented Nov 10, 2012 at 21:18
  • if the user interaction is event based after the new elements are inserted, situation is straightforard. Need to provide a lot more information as to what you expect Commented Nov 10, 2012 at 21:25

1 Answer 1

5

One option would be to dynamically create a style element:

$("<style type='text/css'> .redbold{ color:#f00; font-weight:bold;} </style>").appendTo("head")
$("<div/>").addClass("redbold").appendTo("body");

Taken from here: Create a CSS rule / class with jQuery at runtime.

Here's a possible IE alternative (see Creating a CSS class in jQuery):

document.styleSheets[0].addRule('body', 'background: green', -1);

For reference, see the documentation for addRule.

answered Nov 10, 2012 at 21:21

2 Comments

can't insert css rules directly into head tag without a style tag. Older IE versions don't do well with appended style tags either
@charlietfl - I messed up when pasting in the code (new to SO). Also added a possible alternative for IE.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.