How to get all CSS of element
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;
}
How can I grab all css styles of an element?
UPDATE: As @tank answers below, Chrome version 77 added "Copy Styles" when you right-click on an element in the devtools inspector.
Using Javascript worked best for me. Here's how I did it:
- Open Chrome DevTools console.
Paste this
dumpCSSText
function from this stack overflow answer into the console, and hitEnter
: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;
}When using Chrome, you can inspect an element and access it in the console with the
$0
variable. Chrome also has acopy
command, so use this command to copy ALL the css of the inspected element:copy(dumpCSSText($0));
Paste your CSS wherever you like! /p>
Can jQuery get all CSS styles associated with an element?
A couple years late, but here is a solution that retrieves both inline styling and external styling:
function css(a) {
var sheets = document.styleSheets, o = {};
for (var i in sheets) {
var rules = sheets[i].rules || sheets[i].cssRules;
for (var r in rules) {
if (a.is(rules[r].selectorText)) {
o = $.extend(o, css2json(rules[r].style), css2json(a.attr('style')));
}
}
}
return o;
}
function css2json(css) {
var s = {};
if (!css) return s;
if (css instanceof CSSStyleDeclaration) {
for (var i in css) {
if ((css[i]).toLowerCase) {
s[(css[i]).toLowerCase()] = (css[css[i]]);
}
}
} else if (typeof css == "string") {
css = css.split("; ");
for (var i in css) {
var l = css[i].split(": ");
s[l[0].toLowerCase()] = (l[1]);
}
}
return s;
}
Pass a jQuery object into css()
and it will return an object, which you can then plug back into jQuery's $().css()
, ex:
var style = css($("#elementToGetAllCSS"));
$("#elementToPutStyleInto").css(style);
:)
How get all computed css properties of element and its children in Javascript
Here is something I came up with, basically pass the element you want to extract the styles of and ones of its children, and it will return you the stylesheet as a string. Open your console before running the snippet and you will see the output from the console.log
.
Because I wanted to support the extraction of every element even those without a selector, I had to replace each element id by a unique uuid specifically generated for them in order to facilitate the styling of your output. The problem with this approach is in case you are using ids for styling or for user interaction, you are going to loose such functionality on concerned elements after calling extractCSS
.
However, it is pretty trivial to use the oldId
I'm passing to change back once your pdfKit
process finished the generation. Simply call swapBackIds
passing the elements
returned by the function. You can see the difference of behavior if you uncomment the call in my snippet: the #root
pink background would disappear because the styling targets an element id
.
All in all, you need to:
- Call
extractCSS
with the element you want to extract - Generate your pdf using
res.stylesheet
- Call
swapBackIds
withres.elements
// Generate an unique id for your element
// From https://stackoverflow.com/a/2117523/2054072
function uuidv4 () {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
// Flatten an array
// https://stackoverflow.com/a/15030117/2054072
function flatten(arr) {
return arr.reduce(function (flat, toFlatten) {
return flat.concat(Array.isArray(toFlatten) ? flatten(toFlatten) : toFlatten);
}, []);
}
function recursiveExtract (element) {
var id = uuidv4()
var oldId = element.id
var computed = window.getComputedStyle(element)
var style = computed.cssText
// Now that we get the style, we can swap the id
element.setAttribute('id', id)
// The children are not a real array but a NodeList, we need to convert them
// so we can map over them easily
var children = Array.prototype.slice.call(element.children)
return [{ id: id, style: style, oldId: oldId }].concat(children.map(recursiveExtract))
}
function extractCSS (element) {
if (!element) { return { elements: [], stylesheet: '' } }
var raw = recursiveExtract(element)
var flat = flatten(raw)
return {
elements: flat,
stylesheet: flat.reduce(function (acc, cur) {
var style = '#' + cur.id + ' {\n' + cur.style + '\n}\n\n'
return acc + style
}, '')
}
}
var pdfElement = document.querySelector('#root')
var res = extractCSS(pdfElement)
console.log(res.stylesheet)
function swapBackIds (elements) {
elements.forEach(function (e) {
var element = document.getElementById(e.id)
element.setAttribute('id', e.oldId)
})
}
swapBackIds(res.elements)
#root {
background-color: pink;
}
.style-from-class {
background-color: red;
width: 200px;
height: 200px;
}
.style-from-id {
background-color: green;
width: 100px;
height: 100px;
}
<div id="root">
<span>normal</span>
<span style="background: blue">inline</span>
<div class="style-from-class">
style-class
</div>
<div class="style-from-id">
style-id
<div style="font-size: 10px">a very nested</div>
<div style="font-size: 12px; color: white">and another</div>
</div>
</div>
<div id="ignored-sibling">
</div>
Getting all css used in html file
For inline stylesheets, you can get the content out of the normal DOM like with any other element:
document.getElementsByTagName('style')[0].firstChild.data
For external, link
ed stylesheets it's more problematic. In modern browsers, you can get the text of every rule (including inline, linked and @imported stylesheets) from the document.styleSheets[].cssRules[].cssText
property.
Unfortunately IE does not implement this DOM Level 2 Style/CSS standard, instead using its own subtly different version of the StyleSheet and CSSRule interfaces. So you need some sniff-and-branch code to recreate rules in IE, and the text might not be exactly the same as the original. (In particular, IE will ALL-CAPS your property names and lose whitespace.)
var css= [];
for (var sheeti= 0; sheeti<document.styleSheets.length; sheeti++) {
var sheet= document.styleSheets[sheeti];
var rules= ('cssRules' in sheet)? sheet.cssRules : sheet.rules;
for (var rulei= 0; rulei<rules.length; rulei++) {
var rule= rules[rulei];
if ('cssText' in rule)
css.push(rule.cssText);
else
css.push(rule.selectorText+' {\n'+rule.style.cssText+'\n}\n');
}
}
return css.join('\n');
Get all CSS properties for a class or id with Javascript/JQuery
Use document#styleSheets and extract all rules from all stylesheets into array. Then filter the array by the selectorText
.
Note: I've used a simple Array#includes to check if the requested selector appears in selectorText
, but you might want to create a stricter check to prevent false positives. For example the selector text .demo
can find rules for .demogorgon
as well.
const findClassRules = (selector, stylesheet) => { // combine all rules from all stylesheets to a single array const allRules = stylesheet !== undefined ? Array.from((document.styleSheets[stylesheet] || {}).cssRules || []) : [].concat(...Array.from(document.styleSheets).map(({ cssRules }) => Array.from(cssRules))); // filter the rules by their selectorText return allRules.filter(({ selectorText }) => selectorText && selectorText.includes(selector)); };
console.log(findClassRules('.demo', 0));
.demo { color: red;}
.demo::before { content: 'cats';}
Related Topics
How to Open a File Browser with Default Directory in JavaScript
"Status Code:200 Ok (From Serviceworker)" in Chrome Network Devtools
Ckeditor: Class or Id for Editor Body
Set the Webkit-Keyframes From/To Parameter with JavaScript
Positioning Multiple, Random Sized, Absolutely Positioned Elements So They Don't Overlap
How to Raw Url Encode/Decode in JavaScript and Ruby to Get the Same Values in Both
How to Use JavaScript Source Maps (.Map Files)
Find Dom Element by Id When Id Contains Square Brackets
Addeventlistener with Ajax Not Working Well
Making Sure at Least One Checkbox Is Checked
How to Do Page Numbering in Header/Footer HTMLs with Wkhtmltopdf
Add CSS Styled Marker to Google Maps
How to Increase the Font Size Based on the Window Width
How to Reset :After/:Before CSS Rules for an Element