I am dynamically inserting some html on a web page (after I detect an event from the user). This html needs some css styling and I am wondering what is the cleanest way to do it, using jQuery. I am not the website developer, so I can't add those rules to the original css.
Assume I have already inserted some html without styling, including a formElement
class. I can write in my document a new <style>
block, for instance:
my_html = '<style type="text/css">';
my_html += ' .formElement {';
my_html += ' display: block;';
my_html += ' width: 240px;';
my_html += ' position: relative;';
my_html += ' padding: 4px 0;';
my_html += ' }';
my_html += '</style>';
my_html = $(my_html);
$('body').prepend(my_html);
Or, I can use the css
method:
$('.formElement').css({
'display': 'block',
'width': '240px',
'position': 'relative',
'padding': '4px 0'
});
Which solution is the best/cleanest?
EDIT:
As I can't directly add the rules in the CSS, I will stick with the css
method of jQuery. Some other related questions provide solutions as well:
I can't really use jQuery plugins, but if I could, I would certainly use jQuery.Rule
Thank you all for your precious help.
Don't mix css and js together, especially if your properties don't contain computed or dynamic values: just define a CSS class
.mystyle {
display: block;
width: 240px;
position: relative;
padding: 4px 0;
}
and set the class
$('.formElement').addClass('mystyle');
This:
$('.formElement').css({
'display': 'block',
'width': '240px',
'position': 'relative',
'padding': '4px 0'
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With