29

I have been testing the Javascript CSS functions today and noticed that when .style.cssText is used it only gives me the CSS that i set with JS.

I instead wanted to get all of the CSS for the elements so i am guessing that i am doing something wrong or perhaps need another function instead like getComputedStyle but for the whole CSS rather than single property values but i cannot find what i need when searching.

So my question is how can i get the full CSS from the last part of my code like:

background-color: #ffcccc; font-family:"Helvetica Neue", Arial, "Lucida Grande", sans-serif; font-size: 13px; color: #ff0000; 

instead of the current shorter CSS that is output?

<html>
<head>

<style type="text/css" media="screen">
    .MyDiv001 {
        background-color: #ffcccc;
        font-family:"Helvetica Neue", Arial, "Lucida Grande", sans-serif;
    }
    .MyDiv002 {
        background-color: #ccffcc;
        font-family:"Helvetica Neue", Helvetica, Arial, sans-serif;
    }
</style>

</head>

<body>

<div id="MyDiv001" class="MyDiv001">This is MyDiv001</div>
<div id="MyDiv002" class="MyDiv002">This is MyDiv002</div>
<br /><hr><br />

<script type="text/javascript">

// Select the MyDiv001 element
var MyDiv001 = document.getElementById("MyDiv001"); // Select MyDiv001

// Set some style property values for MyDiv001
MyDiv001.style.setProperty("font-size", "13px", null);
MyDiv001.style.setProperty("color", "#ff0000", null);

// Get the Computed Style for MyDiv001
var MyDiv001Style = window.getComputedStyle(MyDiv001);

// Show the MyDiv001 style property values
document.write( "MyDiv001 background-color = " + MyDiv001Style.getPropertyValue("background-color") + "<br />");
document.write( "MyDiv001 font-family = " + MyDiv001Style.getPropertyValue("font-family") + "<br />");
document.write( "MyDiv001 font-size = " + MyDiv001Style.getPropertyValue("font-size") + "<br /><br />");

// Select the MyDiv002 element
var MyDiv002 = document.getElementById("MyDiv002"); // Select MyDiv002

// Set some style property values for MyDiv002
MyDiv002.style.setProperty("font-size", "16px", null);
MyDiv002.style.setProperty("color", "#0000ff", null);

// Get the Computed Style for MyDiv002
var MyDiv002Style = window.getComputedStyle(MyDiv002); 

// Show the MyDiv002 style property values
document.write( "MyDiv002 background-color = " + MyDiv002Style.getPropertyValue("background-color") + "<br />");
document.write( "MyDiv002 font-family = " + MyDiv002Style.getPropertyValue("font-family") + "<br />");
document.write( "MyDiv002 font-size = " + MyDiv002Style.getPropertyValue("font-size") + "<br /><br />");

// Not what i was expecting
document.write( "MyDiv001 CSS = " + MyDiv001.style.cssText+ "<br />"); // How do i get the full css?
document.write( "MyDiv002 CSS = " + MyDiv002.style.cssText+ "<br />"); // How do i get the full css?

</script>

</body>
</html>

Edit - I would like a answer that uses regular Javascript if possible, hopefully a fixed version of my code and the reason why it does not return the full CSS, thanks.

zeddex
  • 1,260
  • 5
  • 21
  • 38
  • 1
    possible duplicate of [Can jQuery get all CSS styles associated with an element?](http://stackoverflow.com/questions/754607/can-jquery-get-all-css-styles-associated-with-an-element) – Minko Gechev Feb 21 '13 at 10:44
  • 3
    No it's not, thats using jQuery while i have regular JS in the above code. I also want to learn what i have done wrong so i know why it's not returning all of the elements CSS back. – zeddex Feb 21 '13 at 10:53
  • Found an article http://www.quirksmode.org/dom/getstyles.html - I'm no expert on js but seems fairly straight forward – ggdx Feb 21 '13 at 13:47
  • Which is what i originally wanted, i also wanted to learn where i was going wrong but then my question was linked to a off topic one and called a duplicate when it is not, so i then edited my post to make what i thought would be obvious to everyone already more clear. – zeddex Feb 21 '13 at 21:06

6 Answers6

48

MyDiv001.style.cssText will return only inline styles, that was set by style attribute or property.

You could use getComputedStyle to fetch all styles applied to element. You could iterate over returned object to dump all styles.

function dumpCSSText(element){
  var s = '';
  var o = getComputedStyle(element);
  for(var i = 0; i < o.length; i++){
    s+=o[i] + ':' + o.getPropertyValue(o[i])+';';
  }
  return s;
}
Nathan Tuggy
  • 2,237
  • 27
  • 30
  • 38
Ivan Solntsev
  • 2,081
  • 2
  • 31
  • 40
  • This works great for getting the full style. I am still interested in knowing why my code was not working but this basically sorts what i was trying to do, many thanks. – zeddex Feb 21 '13 at 21:08
  • From MDC: [element.style](https://developer.mozilla.org/en-US/docs/DOM/element.style) is not useful for learning about the element's style in general, since it represents only the CSS declarations set in the element's inline `style` attribute, not those that come from style rules elsewhere, such as style rules in the `` section, or external style sheets. – Ivan Solntsev Feb 22 '13 at 07:29
3

Beware that getComputedStyle literally returns the computed values. Meaning relative units such as em will be returned as computed px values (as seen in the computed tab of your browser's devtools).

Depending on your desired outcome, this might completely invalidate it as a viable solution. The other answers - including the accepted one - have failed to mention it entirely, though.

Not enough rep to comment hence this separate answer.

pcjmfranken
  • 33
  • 1
  • 6
1

It's 2020 and we can finally just do

getComputedStyle(element).cssText

Example:

newElement.style.cssText = getComputedStyle(element).cssText

Gabriel Petersson
  • 8,434
  • 4
  • 32
  • 41
  • 1
    Note that this [only gets the inline styles](https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleDeclaration/cssText) of an element (manually set on the element in the HTML, or attached via javascript), not any styles defined through stylesheets. Also the original question starts off by mentioning this method and how it's not sufficient. – V. Rubinetti Jan 26 '22 at 16:13
  • I have a question where I can write this code? what should I put for `element`? – Farhang Amaji May 19 '22 at 22:25
  • 1
    @FarhangAmaji a html element object, from `document.getElementById()` for example – Gabriel Petersson May 20 '22 at 17:36
  • @GabrielPetersson Sorry I didn't read it well, but pls answer where I should put this code? – Farhang Amaji May 21 '22 at 18:42
0

let divStyle1 = document.body.style.cssText; alert(divStyle1);

Boheyga
  • 52
  • 5
0

Here is util function for getComputedStyle to get all or filtered styles for the given css selector of element.

// Select the MyDiv001 element
var MyDiv001 = document.getElementById("MyDiv001"); // Select MyDiv001

// Set some style property values for MyDiv001
MyDiv001.style.setProperty("font-size", "44px", null);
MyDiv001.style.setProperty("color", "rgb(255, 255, 0)", null);


// Get the Computed Style for MyDiv001
var MyDiv001Style = window.getComputedStyle(MyDiv001);

// Show the MyDiv001 style property values
console.log( "MyDiv001 background-color = " + MyDiv001Style.getPropertyValue("background-color") + "<br />");
console.log( "MyDiv001 font-family = " + MyDiv001Style.getPropertyValue("font-family") + "<br />");
console.log( "MyDiv001 font-size = " + MyDiv001Style.getPropertyValue("font-size") + "<br /><br />");


const cssText = (cssSelector, stylesArr = null) => {
  const ele = document.querySelector(cssSelector);
  return Object.entries(getComputedStyle(ele))
    .filter(([k]) => stylesArr?.includes(k) ?? true)
    .map(([k, v]) => `${k}:${v}`)
    .join(";");
};

const myCssText = cssText("#MyDiv001", [
  "backgroundColor",
  "fontFamily",
  "fontSize",
  "color",
]);
console.log({myCssText});

const allCssText = cssText("#MyDiv001");
console.log({allCssText});
    .MyDiv001 {
        background-color: #ffcccc;
        font-family:"Helvetica Neue", Arial, "Lucida Grande", sans-serif;
    }
    .MyDiv002 {
        background-color: #ccffcc;
        font-family:"Helvetica Neue", Helvetica, Arial, sans-serif;
    }
<div id="MyDiv001" class="MyDiv001">This is MyDiv001</div>
<div id="MyDiv002" class="MyDiv002">This is MyDiv002</div>
Siva K V
  • 10,561
  • 2
  • 16
  • 29
-1

Why not just

`
const elt = document.querySelector("element");

function test(){
    console.dir(getComputedStyle(elt, null));
}

test();
`