Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply CSS string using Javascript/jQuery without parsing/tokenizing to retrieve property-value pairs?

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.

like image 794
slackwing Avatar asked Feb 12 '13 10:02

slackwing


2 Answers

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

like image 133
T.J. Crowder Avatar answered Sep 20 '22 11:09

T.J. Crowder


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 .

like image 40
Vanilla Avatar answered Sep 18 '22 11:09

Vanilla