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

Tags: javascript,jquery,css

Problem :

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.

Solution :

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

    CSS Howto..

    How to find number of style classes defined in a CSS file

    How to target items

    how do i get images to display in a rows like this using php and css?

    How to make form line up?

    How to set a fixed background with CSS?

    How to use CSS property position:fixed with top:50px and height:100%?

    How to stop jitter of relatively placed items on scrolling with mouse?

    How to add atributes on pic stored from database [closed]

    How to create a line break instead of having text going on top of itself?

    How to create CSS for round, responsive, bootstrap button with border? Border is affecting pixels

    How to make a centered, responsive CSS circle within a Boostrap div?

    How do I show my existing rails app differently on Facebook canvas

    How to change rows in css from 3x3 on desktop, to 2x4 on mobile?

    How to have a hidable paragraph in an HTML email template

    How to show a title in the border of a div [duplicate]

    How to make a descriptions list inline?

    How to make a themeable web application using CSS?

    How to blur one side of the div using CSS

    How to display a side panel on the left and Google maps api canvas on the right, filling remainder of page?

    CSS: How to get position and size relative to screen width?

    how to nest css boxes with relative positioning and absolute positioning

    Can somebody explain how I should use @font-face for my site?

    Can't show Combobox in table

    How to set font style light?

    How to create three columns in css

    how to center a div in a td cell and a link inside of it ?both vertically and horizontally?

    my website not worked in Ipad and how I can fix some small issue? [closed]

    How is Bootstrap's `nav` class making anchors move to their own line

    How to pull all CSS rules on an element together

    How to change scrollbar css at runtime with javascript?