How to Get All the Applied Styles of an Element by Just Giving Its Id

How to get all the applied styles of an element by just giving its id?

Use the following method:

  • Loop through the indexes of the CSSStyleDeclaration object (getComputedStyle) to get each known property name. Use getPropertyValue + this name to get the value.

    Code optimalization: Do not use getComputedStyle for each iteration, but store it in a variable outside the loop.
  • Use an ordinary for ( name in object ) loop for currentStyle.
  • Use the same looping method for inline styles

Code:

function getStyleById(id) {
return getAllStyles(document.getElementById(id));
}
function getAllStyles(elem) {
if (!elem) return []; // Element does not exist, empty list.
var win = document.defaultView || window, style, styleNode = [];
if (win.getComputedStyle) { /* Modern browsers */
style = win.getComputedStyle(elem, '');
for (var i=0; i<style.length; i++) {
styleNode.push( style[i] + ':' + style.getPropertyValue(style[i]) );
// ^name ^ ^ value ^
}
} else if (elem.currentStyle) { /* IE */
style = elem.currentStyle;
for (var name in style) {
styleNode.push( name + ':' + style[name] );
}
} else { /* Ancient browser..*/
style = elem.style;
for (var i=0; i<style.length; i++) {
styleNode.push( style[i] + ':' + style[style[i]] );
}
}
return styleNode;
}

How to get the applied style from an element, excluding the default user agent styles

There is a read only property of document called 'styleSheets'.

var styleSheetList = document.styleSheets;

https://developer.mozilla.org/en-US/docs/Web/API/Document/styleSheets

By using this, you can reach all the styles which are applied by the author.

There is a similar question about this but not a duplicate, in here:

Is it possible to check if certain CSS properties are defined inside the style tag with Javascript?

You can get the applied style from an element, excluding the default user agent styles using the accepted answer of that question i just mentioned.

That answer didn't supply the element's own style attribute content, so i have improved the code a bit:

var proto = Element.prototype;var slice = Function.call.bind(Array.prototype.slice);var matches = Function.call.bind(proto.matchesSelector ||                 proto.mozMatchesSelector || proto.webkitMatchesSelector ||                proto.msMatchesSelector || proto.oMatchesSelector);
// Returns true if a DOM Element matches a cssRulevar elementMatchCSSRule = function(element, cssRule) { return matches(element, cssRule.selectorText);};
// Returns true if a property is defined in a cssRulevar propertyInCSSRule = function(prop, cssRule) { return prop in cssRule.style && cssRule.style[prop] !== "";};
// Here we get the cssRules across all the stylesheets in one arrayvar cssRules = slice(document.styleSheets).reduce(function(rules, styleSheet) { return rules.concat(slice(styleSheet.cssRules));}, []);

var getAppliedCss = function(elm) { // get only the css rules that matches that element var elementRules = cssRules.filter(elementMatchCSSRule.bind(null, elm)); var rules =[]; if(elementRules.length) { for(i = 0; i < elementRules.length; i++) { var e = elementRules[i]; rules.push({ order:i, text:e.cssText }) } } if(elm.getAttribute('style')) { rules.push({ order:elementRules.length, text:elm.getAttribute('style') }) } return rules;}

function showStyle(){var styleSheetList = document.styleSheets;// get a reference to an element, then...var div1 = document.getElementById("div1");
var rules = getAppliedCss(div1);
var str = '';for(i = 0; i < rules.length; i++) { var r = rules[i]; str += '<br/>Style Order: ' + r.order + ' | Style Text: ' + r.text; } document.getElementById("p1").innerHTML = str;
}
#div1 {float:left;width:100px;}
div {text-align:center;}
<div id="div1" style="font-size:14px;"> Lorem ipsum  </div><br/><br/><a href="javascript:;" onclick="showStyle()"> Show me the style. </a> <p id="p1"><p>

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;
}

Find all CSS rules that apply to an element

EDIT: This answer is now deprecated and no longer works in Chrome 64+. Leaving for historical context. In fact that bug report links back to this question for alternative solutions to using this.


Seems I managed to answer my own question after another hour of research.

It's as simple as this:

window.getMatchedCSSRules(document.getElementById("description"))

(Works in WebKit/Chrome, possibly others too)

In GWT how to know all the styles applied to a given element (by id or class name)

Found a solution to my problem (in fact two but I'm going for the first) :

  1. Using jQuery's css() that does what I wanted
  2. A pure javascript solution in this SO question

I now just have to write a JNSI wrapper for the jQuery function...

Edit : Found a third solution which correspond exactly to what I want : GQuery which is a port of jQuery to GWT and contains (according to the main page) 98% of jQuery's core functionalities.

How to apply CSS style to all elements with same ID using one button?

Your code is only every going to update one element, because getElementById will only ever return one element (because, as we've said, id is supposed to be unique). If you need to mark multiple elements as related use a class instead. Here is a working example using class, JavaScript:

function change() {
var test = document.getElementById("button1");
var els = document.getElementsByClassName("p2");
if (test.value == "Hide Spoiler") {
test.value = "Open Spoiler";
for (var i=0; i<els.length; i++) {
els[i].style.backgroundColor = "black";
}
} else {
test.value = "Hide Spoiler";
for (var i=0; i<els.length; i++) {
els[i].style.color = "black";
els[i].style.backgroundColor = "transparent";
}
}
}

HTML:

<input onclick="change()" type="button" value="Hide Spoiler" id="button1"></input>
<br>
<span class="p2">Hidden text</span> Test for more <span class="p2">Hidden text</span> test again. <span class="p2">Hidden text</span>

If you need it to work in browsers too old for getElementsByClassName, try using jQuery. It makes this sort of thing lots easier

jQuery - How to get all styles/css (defined within internal/external document) with HTML of an element

outerHTML (not sure, you need it — just in case)

Limitations: CSSOM is used and stylesheets should be from the same origin.

function getElementChildrenAndStyles(selector) {
var html = $(selector).outerHTML();

selector = selector.split(",").map(function(subselector){
return subselector + "," + subselector + " *";
}).join(",");
elts = $(selector);

var rulesUsed = [];
// main part: walking through all declared style rules
// and checking, whether it is applied to some element
sheets = document.styleSheets;
for(var c = 0; c < sheets.length; c++) {
var rules = sheets[c].rules || sheets[c].cssRules;
for(var r = 0; r < rules.length; r++) {
var selectorText = rules[r].selectorText;
var matchedElts = $(selectorText);
for (var i = 0; i < elts.length; i++) {
if (matchedElts.index(elts[i]) != -1) {
rulesUsed.push(rules[r]); break;
}
}
}
}
var style = rulesUsed.map(function(cssRule){
if (cssRule.style) {
var cssText = cssRule.style.cssText.toLowerCase();
} else {
var cssText = cssRule.cssText;
}
// some beautifying of css
return cssText.replace(/(\{|;)\s+/g, "\$1\n ").replace(/\A\s+}/, "}");
// set indent for css here ^
}).join("\n");
return "<style>\n" + style + "\n</style>\n\n" + html;
}

usage:

getElementChildrenAndStyles("#divId");

Applying CSS styles to all elements inside a DIV

You could try:

#applyCSS .ui-bar-a {property:value}
#applyCSS .ui-bar-a .ui-link-inherit {property:value}

Etc, etc... Is that what you're looking for?



Related Topics



Leave a reply



Submit