Finding All CSS Rules (including "invalid rules") Via Javascript - javascript

I am trying to use document.styleSheets to add a shim for CSS calc functionality.
Basically I am looping over each stylesheet and it's subsequent rules and looking for calc to occur somewhere, and doing the calculation in JavaScript and applying it to the associated element.
This is MUCH faster than looping over every element on the page and trying to find if it has a failed calc rule, but the problem is I do not see a way to pull in errored CSS rules through this method. Both rules and cssRules arrays contain only CSS that the browsers considers valid.
My question is this, is there a way to get these invalid CSS values through this method?
The code I am using is below, and works, but only on browsers that support calc anyways, which is useless to me. I need to be able to get ALL of the css rules as they appeared in the loaded CSS document in order to make this work.
Is this possible or am I barking up an imaginary fantasy tree of cross-browser calc awesomeness?
calcShim = function(){
var stylesheets = document.styleSheets;
var calcs = [];
for (var i=0, j=stylesheets.length; i<j; i++){
var stylesheet = stylesheets[i];
var rules = stylesheet.cssRules;
if (rules && rules.length > 0){
for (var k=0, l=rules.length; k<l; k++){
var rule = rules[k];
var ruleText = String(rule.cssText);
if (ruleText.match("calc")){
calcs.push(ruleText);
};
};
}
};
for (var i=0, j=calcs.length; i<j; i++){
var string = calcs[i];
var reference = calcs[i].match(/^[^{]{1,}/g)[0];
var objects = $(reference);
for (var k=0, l=objects.length; k<l; k++){
var object = $(objects[k]);
var parent = object.parent();
if (parent.is(":visible")){
var parentWidth = parseInt(parent.width());
var percent = parseInt(string.match(/(?:calc\()([0-9]{1,3})(?=%)/)[1])/100;
var operator = string.match(/(?:calc[^)]{1,})([\+\-\*\/])(?=\s[0-9]{1,3}px)/)[1];
var value = parseInt(string.match(/(?:calc[^)]{1,}[\+\-\*\/]\s)([0-9]{1,3})(?=px)/)[1]);
var mathString = (parentWidth*percent) + " " + operator + " " + value;
var result = eval(mathString);
object.css({"width": result});
}
};
};
};
I am aware this code could be better/cleaner, I was just trying to come up with a proof of concept.

Related

Is there a way to loop this?

Is there a way to loop a declaration of a variable? just a loop to help me declare the variables so i dont have to do the monotonous work of change the numbers of the variable
var height1 = document.getElementById('height1').value;
var height2 = document.getElementById('height2').value;
var height3 = document.getElementById('height3').value;
var height4 = document.getElementById('height4').value;
var height5 = document.getElementById('height5').value;
var height6 = document.getElementById('height6').value;
var height7 = document.getElementById('height7').value;
var height8 = document.getElementById('height8').value;
var height9 = document.getElementById('height9').value;
var height10 = document.getElementById('height10').value;
var height11 = document.getElementById('height11').value;
var height12 = document.getElementById('height12').value;
var height13 = document.getElementById('height13').value;
var height14 = document.getElementById('height14').value;
var height15 = document.getElementById('height15').value;
var height16 = document.getElementById('height16').value;
This is not a right way of coding that, Just do like,
var heights = [];
Array.from(document.querySelectorAll("input[id^=height]")).forEach(function(itm){
heights.push(itm.value);
});
And now you can iterate the array heights to manipulate the values as per your requirement.
The logic behind the code is, querySelectorAll("input[id^=height]") will select the input elements that has id starts with the text height. Since the return value of querySelectorAll is a nodelist, we have to convert it as an array before using array functions over it. So we are using Array.from(nodelist). That will yield an array for us. After that we are iterating over the returned array by using forEach and pushing all element's value into the array heights.
This is almost always an indication that you want an array. Something like this:
var heights = [];
for (var i = 1; i <= 16; i++) {
heights.push(document.getElementById('height' + i).value);
}
Then you can reference a value from the array with something like:
heights[1]
Though technically since in JavaScript your window-level variables are indexable properties of the window object, you can essentially do the same thing with variable names themselves:
for (var i = 1; i <= 16; i++) {
window['height' + i] = document.getElementById('height' + i).value;
}
Then you can still use your original variables:
height1
Though in the interest of keeping things outside of window/global scope, maintaining the array seems a bit cleaner (and semantically more sensible).
This seems to be a good use case for an object:
var heights = {};
for (var i = 1; i <= 16; i++) {
heights[i] = document.getElementById('height' + i).value;
}
Maybe its time to introduce function:
Generally speaking, a function is a "subprogram" that can be called by code external (or internal in the case of recursion) to the function. Like the program itself, a function is composed of a sequence of statements called the function body. Values can be passed to a function, and the function will return a value.
function getHeight(id) {
return document.getElementById(id).value;
}
Call with the wanted id and use it like a variable.
getHeight('height1')
Normally you would put them in an array.
var heights = []
for (i = 1; i < 17; i++) {
heights[i] = document.getElementById('height' + i).value;;
}
Beware this will give you a hole at the start of the array ie heights[0] has nothing in it. If you use this to iterate it won't matter...
for (var i in heights) {
alert(heights[i]);
}

How to get a ALL the css properties set on an element with jquery [duplicate]

Is there a way in jQuery to get all CSS from an existing element and apply it to another without listing them all?
I know it would work if they were a style attribute with attr(), but all of my styles are in an external style sheet.
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);
:)
Two years late, but I have the solution you're looking for. Not intending to take credit form the original author, here's a plugin which I found works exceptionally well for what you need, but gets all possible styles in all browsers, even IE.
Warning: This code generates a lot of output, and should be used sparingly. It not only copies all standard CSS properties, but also all vendor CSS properties for that browser.
jquery.getStyleObject.js:
/*
* getStyleObject Plugin for jQuery JavaScript Library
* From: http://upshots.org/?p=112
*/
(function($){
$.fn.getStyleObject = function(){
var dom = this.get(0);
var style;
var returns = {};
if(window.getComputedStyle){
var camelize = function(a,b){
return b.toUpperCase();
};
style = window.getComputedStyle(dom, null);
for(var i = 0, l = style.length; i < l; i++){
var prop = style[i];
var camel = prop.replace(/\-([a-z])/g, camelize);
var val = style.getPropertyValue(prop);
returns[camel] = val;
};
return returns;
};
if(style = dom.currentStyle){
for(var prop in style){
returns[prop] = style[prop];
};
return returns;
};
return this.css();
}
})(jQuery);
Basic usage is pretty simple, but he's written a function for that as well:
$.fn.copyCSS = function(source){
  var styles = $(source).getStyleObject();
  this.css(styles);
}
Why not use .style of the DOM element? It's an object which contains members such as width and backgroundColor.
I had tried many different solutions. This was the only one that worked for me in that it was able to pick up on styles applied at class level and at style as directly attributed on the element. So a font set at css file level and one as a style attribute; it returned the correct font.
It is simple! (Sorry, can't find where I originally found it)
//-- html object
var element = htmlObject; //e.g document.getElementById
//-- or jquery object
var element = htmlObject[0]; //e.g $(selector)
var stylearray = document.defaultView.getComputedStyle(element, null);
var font = stylearray["font-family"]
Alternatively you can list all the style by cycling through the array
for (var key in stylearray) {
console.log(key + ': ' + stylearray[key];
}
#marknadal's solution wasn't grabbing hyphenated properties for me (e.g. max-width), but changing the first for loop in css2json() made it work, and I suspect performs fewer iterations:
for (var i = 0; i < css.length; i += 1) {
s[css[i]] = css.getPropertyValue(css[i]);
}
Loops via length rather than in, retrieves via getPropertyValue() rather than toLowerCase().

accessing nested properties based on structure

Could anyone please give me an alternate syntax to the following
var id = '-JLxSeCPUCVN13FxifTY';
var ResultsContainer = results[id];
var i=0;
for(var k in ResultsContainer)
{
var TheArrayOfObjectsThatIneed = ResultsContainer[Object.keys(ResultsContainer)[i]];
console.log(TheArrayOfObjectsThatIneed);
//loop the TheArrayOfObjectsThatIneed do the processing
i++;
}
as you see in the image i have an array within an object within an object and i have no idea what the property names are but the structure is always the same {results:{id:{idthatidontknow:[{}]}}} and all i need is to access the arrays
the above code is working nicely but i am new to javescript and i was wondering if there is a nicer syntax and if i am doing it the right way
Perhaps something like this?
var id = '-JLxSeCPUCVN13FxifTY';
var ResultsContainer = results[id];
for(var k in ResultsContainer) {
if (ResultsContainer.hasOwnProperty(k)) {
var TheArrayOfObjectsThatIneed = ResultsContainer[k];
console.log(TheArrayOfObjectsThatIneed);
//loop the TheArrayOfObjectsThatIneed do the processing
}
}

jquery: Get full css property set as string from an element [duplicate]

Is there a way in jQuery to get all CSS from an existing element and apply it to another without listing them all?
I know it would work if they were a style attribute with attr(), but all of my styles are in an external style sheet.
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);
:)
Two years late, but I have the solution you're looking for. Not intending to take credit form the original author, here's a plugin which I found works exceptionally well for what you need, but gets all possible styles in all browsers, even IE.
Warning: This code generates a lot of output, and should be used sparingly. It not only copies all standard CSS properties, but also all vendor CSS properties for that browser.
jquery.getStyleObject.js:
/*
* getStyleObject Plugin for jQuery JavaScript Library
* From: http://upshots.org/?p=112
*/
(function($){
$.fn.getStyleObject = function(){
var dom = this.get(0);
var style;
var returns = {};
if(window.getComputedStyle){
var camelize = function(a,b){
return b.toUpperCase();
};
style = window.getComputedStyle(dom, null);
for(var i = 0, l = style.length; i < l; i++){
var prop = style[i];
var camel = prop.replace(/\-([a-z])/g, camelize);
var val = style.getPropertyValue(prop);
returns[camel] = val;
};
return returns;
};
if(style = dom.currentStyle){
for(var prop in style){
returns[prop] = style[prop];
};
return returns;
};
return this.css();
}
})(jQuery);
Basic usage is pretty simple, but he's written a function for that as well:
$.fn.copyCSS = function(source){
  var styles = $(source).getStyleObject();
  this.css(styles);
}
Why not use .style of the DOM element? It's an object which contains members such as width and backgroundColor.
I had tried many different solutions. This was the only one that worked for me in that it was able to pick up on styles applied at class level and at style as directly attributed on the element. So a font set at css file level and one as a style attribute; it returned the correct font.
It is simple! (Sorry, can't find where I originally found it)
//-- html object
var element = htmlObject; //e.g document.getElementById
//-- or jquery object
var element = htmlObject[0]; //e.g $(selector)
var stylearray = document.defaultView.getComputedStyle(element, null);
var font = stylearray["font-family"]
Alternatively you can list all the style by cycling through the array
for (var key in stylearray) {
console.log(key + ': ' + stylearray[key];
}
#marknadal's solution wasn't grabbing hyphenated properties for me (e.g. max-width), but changing the first for loop in css2json() made it work, and I suspect performs fewer iterations:
for (var i = 0; i < css.length; i += 1) {
s[css[i]] = css.getPropertyValue(css[i]);
}
Loops via length rather than in, retrieves via getPropertyValue() rather than toLowerCase().

Merging css classes with jQuery/Javascript

I have a problem. I have a bunch webpage that makes heavy use of multiple css classes.
<div class="class1 class2 class3">foo</div>
Unfortunately, I have a "browser" (for lack of a better term) that can not handle multiple css classes in that manner.
I can identify all the elements with multiple classes but now I need to create new classes that merge them. First attempt was to inline all the styles into the style attribute, however that was far too slow, and bloated the document needlessly.
What I now want to do is find an element with multiple classes. Create a new class which is a combination, and replace the elements class with the newly created one, as well as any other elements with the same class combination.
Any thoughts on how best to approach this.
Loop through all tags. Split the class names into an array. Sort it to get it into a predictable order. Join the string back together.
$(document).ready(function() {
var classList = {};
$("*").each(function() {
var temp;
if (this.className) {
temp = this.className.split(" "); // split into array
temp.sort(); // put in predictable order
this.className = temp.join(""); // put class name back without spaces
classList[this.className] = true; // add to list
}
});
// classList object contains full list of all classNames used
});
FYI, it seems really odd that you'd have a browser that supports jQuery, but doesn't support CSS styles for multiple class names. You do realize that you are going to have to supply completely different stylesheets that work off the concatenated names, right? And, if you can change the stylesheets, it makes me wonder why you can't change the HTML.
Working implementation: http://jsfiddle.net/jfriend00/uPET7/
Summary: This function returns an ordered list of all duplicate class names, which can easily be used to merge classes.
To start off, get a useful list of duplicates:
var multi = {};
$("*[class]").each(function(){
var class = this.className.replace(/^\s+|\s+$/g,"").replace(/\s+/g,".");
if(!/\./.test(class)) return; //Ignore single classes
if(multi[class]){
multi[class]++;
} else {
multi[class] = 1;
}
});
//Now, merge duplicates, because .class1.class2 == .class2.class1
var multi_nodup = {};
for(var classes in multi){
var a_classes = classes.split(".");
var a_classes = a_classes.sort();
var a_classes = a_classes.join(".");
if(multi_nodup[a_classes]){
multi_nodup[a_classes] += multi[classes];
} else {
multi_nodup[a_classes] = multi[classes]
}
}
//Now, multi_npdup is a map of all duplicate classnames
var array_multi = [];
for(var classes in multi_nodup){
array_multi.push([multi_nodup[classes], classes]);
}
array_multi.sort(function(x,y){return y[0]-x[0]});
//array_multi is an array which looks like [["class1.class2.class2", 33],
// ["class3.class4", 30], ...]
// = A list, consisting of multiple class names, where multiple classnames
// are shown, together with the nuber of occurences, sorted according to
// the frequence
Execute my function, and output variable array_multi. This will show you a map of multiple class names, so that you can replace multiple classnames, accordingly.
Because of the special way I stored the class names, you can use $("." + array_multi[n][0]) to access all elements which have a set of classname which equals to the set as described at the nth position in array_multi.
Example of readable output:
//Overwrites current document!
var list = "";
for(var i=0; i<array_multi.length; i++) list += array_multi[i][0] + "\t" + array_multi[i][1];
document.open();
document.write("<pre>"+list+"</pre>")
document.close();
Automatic conversion
A way to automate the merging of the classnames i by adding all separate class properties to a JavaScript string, and add it to an object. This is the most reliable way to get the exact CSS properties, because attempting to get the classnames through the document.styleSheets object can produce slightly different results. Example:
var classStyle = {};
classStyle["class1"] = "border:1px solid #000;";
classStyle["class2"] = "color:red";
//Make sure that each declaration ends with a semicolon:
for(var i in classStyle) if(!/;$/.test(classStyle[i])) classStyle[i] += ";";
//Initialise
var all_styles = {};
for(var i=0; i<array_multi.length; i++){
all_styles[array_multi[i][1]] = "";
}
//This loop takes definition precedence into account
for(var currentCName in classStyle){
var currentClass = new RegExp("(?:^|\\.)" + currentCName + "(?:\\.|$)");
// Rare occasion of failure: url("data:image/png,base64;....")
var separateProps = classStyle[currentCName].split(";");
var prop_RE = {};
for(var p=0; p<separateProps.length; p++){
var cssProperty = separateProps[p];
if(!/:/.test(cssProperty)) continue; //Invalid CSS property
prop_RE[cssProperty] = new RegExp("(^|;)\\s*" + cssProperty.match(/(\S+)\s*:/gi)[1] + "\\s*:[^;]+;?", "gi");
}
for(var class in all_styles){
if(currentClass.test(class)){
for(var k in prop_RE){
all_styles[class] = all_styles[class].replace(prop_RE[k],"$1") + k;
}
}
}
}
//To finish off:
var allClassesToString = "";
for(var class in all_styles){
var newClass = class.replace(/\./g, "_");
$("."+class).each(function(){
this.className = newClass;
});
allClassesToString += "."+newClass + "{" + all_styles[class] + "}\n";
}
// allClassesToString <------- This variable now holds a string of all duplicate CSS classes!
//Example:
var style = $("<style>");
style.text(allClassesToString);
style.appendTo($("head:first"));
Does not seem to crazy to accomplish this,
Loop through every element that has more than 1 class. Sort the classes (doesn't matter how as long as it is consistent) then merge them together to create the new class. Keep a list of all new css classes and check against them in case of duplicates.
To get all the styles from an element see here

Categories

Resources