137

I'm attempting to add this code to a dynamically created div element

style = "width:330px;float:left;" 

The code in which creates the dynamic div is

var nFilter = document.createElement('div');
nFilter.className = 'well';
nFilter.innerHTML = '<label>' + sSearchStr + '</label>';

My idea is to add the style after < div class="well" but I don't know how I'd do it.

3
  • 1
    What difference does it make? Inline style will always have the highest specificity. Commented Feb 7, 2013 at 14:13
  • 1
    because the div is dynamically created, i can't use static since it's a complete Javascript library script Commented Feb 7, 2013 at 14:14
  • Maybe this is an XY problem. What are you trying to achieve? Is nFilter.style.width = '330px'; nFilter.style.float = 'left'; what you are looking for? Commented Feb 7, 2013 at 14:15

11 Answers 11

168
nFilter.style.width = '330px';
nFilter.style.float = 'left';

This should add an inline style to the element.

Most CSS names are mapped 1:1 to the JavaScript property. CSS properties with dashes in their names are converted to camel case. For more information see the blue information box at https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style

Sign up to request clarification or add additional context in comments.

Comments

57

You can do it directly on the style:

var nFilter = document.createElement('div');
nFilter.className = 'well';
nFilter.innerHTML = '<label>'+sSearchStr+'</label>';

// Css styling
nFilter.style.width = "330px";
nFilter.style.float = "left";

// or
nFilter.setAttribute("style", "width:330px;float:left;");

1 Comment

Not the CSS styling but the third option with setAttribute worked perfect for me.
25

Using jQuery :

$(nFilter).attr("style","whatever");

Otherwise :

nFilter.setAttribute("style", "whatever");

should work

2 Comments

It is unnecessary to use JQuery in this case
He gives an alternate solution without JQuery. Don't see the need for a downvote.
17

You can try with this

nFilter.style.cssText = 'width:330px;float:left;';

That should do it for you.

Comments

14
var div = document.createElement('div');
div.setAttribute('style', 'width:330px; float:left');
div.setAttribute('class', 'well');
var label = document.createElement('label');
label.innerHTML = 'YOUR TEXT HERE';
div.appendChild(label);

Comments

12

A few people have an example using setAttribute which I like. However it assumes you don't have any styles currently set. I would maybe do something like:

nFilter.setAttribute('style', nFilter.getAttribute('style') + ';width:330px;float:left;');

Or make it into a helper function like this:

function setStyle(el, css){
  el.setAttribute('style', el.getAttribute('style') + ';' + css);
}

setStyle(nFilter, 'width:330px;float:left;');

This makes sure that you can add styles to it continuously and it won't remove any style currently set by always appending to the current styles. It also adds an extra semi colon so that if there is a style ever missing one it will append another to make sure it is fully delimited.

Comments

6

If you don't want to add each css property line by line, you can do something like this:

document.body.insertAdjacentHTML('afterbegin','<div id="div"></div>');

/**
 * Add styles to DOM element
 * @element DOM element
 * @styles object with css styles
 */
function addStyles(element,styles){
  for(id in styles){
    element.style[id] = styles[id];
  }
}

// usage
var nFilter = document.getElementById('div');
var styles = {
  color: "red"
  ,width: "100px"
  ,height: "100px"
  ,display: "block"
  ,border: "1px solid blue"
}
addStyles(nFilter,styles);

1 Comment

this is so cool, it helps me a lot with organizing my plain html css code without framework. thanks a tons!
4

you should make a css class .my_style then use .addClass('.mystyle')

1 Comment

I use element.classList.add("myClass"), it works, is it what you meant? It drives my source code a lot easier to maintain and to understand than other solutions.
1

Use cssText

nFilter.style.cssText +=';width:330px;float:left;';

Comments

1

Try something like this

document.getElementById("vid-holder").style.width=300 + "px";

Comments

-1

Fantastic solution by stuyam I am adding to that

addStyle('img', 'height:auto;max-width:98%;');


function addStyle(elem, cssText) {

 let curstyle;
 
 const arr = document.querySelectorAll(elem);
 
 arr.forEach(function(el){
    // get and save any current image styles
    curstyle = el.getAttribute("style");
    
    if(curstyle){
       curstyle = curstyle.trim();
        // make sure right most character of [curstyle] is [;]
       let lastchr = curstyle.charAt(curstyle.length - 1);
       
       if(lastchr !== ";"){
           curstyle += ";";
       }
    }else{
       curstyle = "";
    }

   el.style.cssText += cssText;
   console.log(el.style.cssText);
 });
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.