Cristian
Cristian

Reputation: 1670

How to set up attribute style using variables?

I have two variables:

customBlock witch is <div class="column" used="true"></div>

customStyle witch is style="background: yellow"

How can I assign the yellow background to the customBlock? One option would be to get the 'yellow' word from the string and use
customBlock.setAttribute('background', yelloVariable)

But I am looking (in javascript not jquery) for something clean like this: customBlock.magic(customStyle)

Upvotes: 0

Views: 41

Answers (2)

grateful
grateful

Reputation: 1128

    var customBlock = "<div id='cB' class='column' used='true'></div>"; //A STRING. NOTE: I GAVE THE DIV AN ID
    var customStyle = "background-color: yellow; width:50px; height:50px"; //I GAVE IT DIMENSIONS SO YOU CAN SEE IT

    var attachColumn = document.body.innerHTML+=customBlock;//ADD CUSTOMBLOCK TO SOMETHING IN THE DOCUMENT - eg. THE BODY
    document.getElementById("cB").style=customStyle; //REFERENCING THE ID OF THE ELEMENT THAT IS NOW IN THE DOM, WE ADD THE STYLE ATTRIBUTE
<body></body>

Upvotes: 0

Jacob Brazeal
Jacob Brazeal

Reputation: 654

EDIT:

1. If you want magic, this is at least a single line:

customBlock.outerHTML = customBlock.outerHTML.split("<div").join("<div " + customStyle);

2. Otherwise

Iterate through the style statements (and I notice belatedly that I treated your customStyle as a style declaration, not as HTML here: that could be easily fixed)

// Break down by semi-colon separated statements
styleList = customStyle.split(";");

//Iterate through
for ( var i=0; i<styleList.length; i++ ) {

    //Break down statement into before and after colon
    var statement = styleList[i].split[":"];

    if ( ! statement[1] ) {
        //No colon: could just be empty statement or the empty string after the last semicolon
         continue;
    }
    //Trim whitespace from key
    var key = statement[0].split(" ").join("");
    //Set style
    customBlock.style[key] = statement[1];

}

EDIT: I just notices that your customStyle is HTML; I treated it here like a valid CSS string.

Upvotes: 1

Related Questions