Jquery – How to get the css with in inline styles using jquery

asp.net-mvccssjquery

I am loading the styles dynamically from the database in my asp.net mvc (C#) application.

I am trying to change some of the properties like (background, font color, font size,…) of the loaded inline style. I am using jquery.rule to do this.

I need to update the complete inline style including the changes, back to the database using jquery.

The inline style inside the head looks like:

<style type="text/css">
    <!
    -- body
    {
        background: #fff;
        margin: 0px;
        padding: 0px;
        font: normal 12px Tahoma, Verdana, Arial;
        color: #636363;
    }
    a
    {
        color: #d0d0d0;
        text-decoration: none;
    }
    #header
    {
        padding-left: 35px;
        height: 60px;
        vertical-align: middle;
        padding-top: 25px;
    }
    -- ></style>

I need to get updated inline style. How to do it?

Best Answer

I need to update the complete inline style including the changes, back to the database using jquery.

Are you trying to read the inline style declarations of an element in the page? If so, this is tricky. In theory you should be able to call element.getAttribute('style') or the jQuery equivalent. However DOM attribute access doesn't work in IE; in fact IE doesn't store the attribute as used in the document at all, only the parsed style declarations that result from it.

There's not a jQuery-specific means of reading all styles, but you can get the effective inline style rules as CSS using DOM Level 2 Style.

var style= element.style.cssText;

But in IE this will separate any shortcut properties you have used, for example setting border can result in you getting border-style, border-color and border-width back. IE will also upper-case the property names. This may or may not matter to you.

You'd probably be better off remembering the inline style changes you make in a separate lookup object so you can read it more easily. You can attach that to the element using jQuery's data() method, make all changes to both the ‘real’ element.style and the lookup $(element).data('stylestore') objects, then retrieve all set styles from the lookup when you're about to post.