I'm the type of person who loves to do a lot of projects especially if it involves only JavaScript since that is my strong point.
I thought of a little fun idea. Writing little pieces of CSS with JavaScript. These CSS pieces could then be used in a Blob or implemented into the webpage some other way.
Most of the time, I do projects just for FUN and for build up in experience.
Let's get more of a feel for what we are working with. One of these JavaScript stylesheets could look like this:
var sheet = {
"h1": {
"font-size": "24px",
"color": "blue",
children: {
"a": {
"font-size": "15px"
}
}
},
"a": {
color: "red"
}
};
This would return:
h1{font-size:24px;color:blue}h1 a{font-size:15px}a{color:red}
Note the children
propert in the h1
element.
This is my way of nesting, making the h1 a
.
My question however is, how could I make a continuous nesting so I could end up with something like:
"h1 div span a"
Meaning that each nested child will need be able to use the children
property.
The script I have so far is below (belongs with the variable sheet
).
var to = "";
for (var el in sheet) {
var props = [];
for (var prop in sheet[el]) {
if(prop != "children") {
props.push(prop + ":" + sheet[el][prop]);
}
}
to += el + "{" + props.join(";") + "}";
//----
if (sheet[el].children) {
for (var el2 in sheet[el].children) {
var props = [];
for (var prop in sheet[el].children[el2]) {
props.push(prop + ":" + sheet[el].children[el2][prop]);
}
to += el + " " + el2 + "{" + props.join(";") + "}"
}
}
//----
}
The sections in between the comments is the code I use for the 1 time nesting.
I'm not sure how difficult this would be to add. But I understand that it probable wouldn't be easy.
My full example is here: http://jsfiddle.net/shawn31313/2tfnz/1
You can pretty easily make your code recursive:
function buildCSS(stub, node){
var to = "";
for (var el in node) {
var rule = stub + " " + el;
var props = [];
for (var prop in node[el]) {
if(prop != "children") {
props.push(prop + ":" + node[el][prop]);
}
}
to += rule + "{" + props.join(";") + "}";
if (node[el].children) {
to += buildCSS(rule, node[el].children);
}
}
return to;
}
var to = buildCSS("", sheet);
This can definitely be cleaned up, but it illustrates the idea.
http://jsfiddle.net/2tfnz/3/
You might also consider a tweak to your object structure to make the code a bit cleaner:
var sheet = {
"h1": {
rules: {
"font-size": "24px",
"color": "blue"
},
children: {
"a": {
rules: {
"font-size": "15px"
}
}
}
},
"a": {
rules: {
color: "red"
}
}
};
In this way, you wouldn't need to distinguish between properties named children
and those which aren't.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With