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..

    CSS - want to remove a blank space but have no idea how to get rid of it?

    how to add class to razor form and give padding?

    how to currency convert in java script

    How to use jQuery to detect loaded background image after inserting out CSS

    How is this font face in CSS3 embedded into a css file?

    How can I set inline css styles for an element with javascript?

    How to resize div with CSS by the border

    How to make flashing text in Css? [duplicate]

    How can I make images stack on top of each other as web page scales down?

    How to change the color of html td element after postback in asp.net?

    CSS - How do I float one element to the right inside the other div?

    How to put logo on navigation bar

    How to find the css class of an anchor link inside a cross domain iFrame?

    How do I get a zooming effect on an image when a user hovers over it? [closed]

    jqueryui dialog with table — how to limit row height

    How do I float a div to the right of a title div without affecting the content of the title?

    Bootstrap with Picture Slideshow

    How to set negative z-index with jQuery?

    How to have a box increase its size based on its content?

    How to fit css textbox to content?

    How to force parent div to expand by child div width/padding/margin/box?

    How to apply a CSS height setting to all child elements?

    How to use background image in CSS?

    How to set continuous box-shadow through all inline-block centered li elements

    Wordpress- How do i change the default font of navigation menu?

    How do you center align inline elements inside an html div?

    How do I keep a CSS hover rule applied when the mouse moves to the child element?

    How to do a webkit css endless rotation-animation.

    How to make Asp.net Gridview header and first column frezee?

    How to fix the heading in html table using css