I have some CSS in string form, e.g.
border: solid 1px #0000ff; background-color: #ffff00;
and I want to apply that CSS to a <div>
. But all of the examples for using jQuery to apply CSS involve using the css
method, and to go that route, I'd have to split the CSS string by semicolons (;
) to retrieve property-value pairs, then by (:
) to retrieve the property and value, and do
$('myDiv').css(property, value);
Is there a way to apply the CSS directly, from its string form?
I worry that such a naive parsing of the CSS (semicolons and colons) will fail if CSS values can contain those characters, e.g. in url
sub-values.
You can retrieve the existing style
attribute and then set a new one:
var target = $("#target");
target.attr("style", target.attr("style") + "; " + yourString);
Live Example | Source
Just use the jQuery's function .attr('style', 'somthing...')
,It's very easy to use and you don't have to think about fault tolerance .
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