Assign CSS value to HTML via JavaScript

1

I created this FIDDLE to see if what I was doing was right or wrong. Apparently it's wrong:

My goal here is to JavaScript assign CSS values to an HTML element, in this case the value top .

Based on the response from this problem which I found, but I do not even have the intended end result that was for div 100px below.

JAVASCRIPT

var altura = 100;

$("#footer").css("top", altura + "px");

HTML

<div id = "footer">
</div>

CSS

#footer {
    height: 100px;
    background-color: grey;
}
    
asked by anonymous 01.06.2015 / 16:37

3 answers

1

To work with element positions, TOP, LEFT, RIGHT, BOTTOM you MUST use the Position property with Relative, Absolute, Fixed values ...

Otherwise you can use Margin-Top , worth 100px.

Change your CSS to:

#footer {
    height: 100px;
    background-color: grey;
    position:relative; // Note aqui a propriedade Position
}
    
01.06.2015 / 16:43
1

msm.oliveira, I saw in the comments that you would like to pass more parameters. Follow the code as an example with more than one parameter.

$('elemento').css({ 'atributo':'Valor', 'atributo':'Valor', 'atributo':'Valor', });

or for a better code reading:

$('elemento').css({
    'atributo':'Valor',
    'atributo':'Valor',
    'atributo':'Valor',
});

Note that the attribute / value pairs must now be enclosed in single quotes or quotation marks, and should be separated by: (colon) and not more by commas, the comma is now used to separate the attributes you want to manipulate. / p>     

01.06.2015 / 22:42
0

Using Javascript pure, if you do not want / can use jquery:

var elemento = document.querySelector("#teste");
elemento.style.backgroundColor = "#D93600";
    
03.06.2015 / 18:52