Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Get all the CSS styles associated with an element

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 93
    Comment on it

    Hello

    Today we will discuss about the ways in which we can get all the CSS styles associated to an element.

    The CSS styles to an element can be applied in two ways:

    - using inline styles

    e.g.

     <div style="border:solid #000 2px; overflow:hidden; width:250px; height:10px id=inlineStyle">
    </div>
    


    - using external CSS

    e.g.

    <div  id="stylediv"></div>
    
    div {
    
    border:solid #000 2px; overflow:hidden; width:250px; height:10px
    
    }
    


    if we want to get the CSS styles applied using the style attribute

    $(document).ready(function()
    
      {      
    
        alert($("#inlineStyle").attr('style'));
    
      });
    


    if we want to get all the CSS styles applied to an element including inline and external styles we can use the getComputedStyle method

    var el = document.getElelmentById("stylediv") // get the div based on ID
        var style = window.getComputedStyle(el); // get all the CSS styles
        return Object.keys(style).reduce(function(acc, k) {
            var name = style[k],
                value = style.getPropertyValue(name); // check the values for all the styles
            if (value !== null) { // check if the style value is not null
                acc[name] = value;
            }
            return acc; // returns all the styles associated to the element el
        }, {});
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: