Assign CSS value to an HTML via Javascript

Asked

Viewed 2,938 times

1

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

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

I was basing my response on this problem which I found, but even I do not have the final result intended which was to put the div 100px further down.

JAVASCRIPT

var altura = 100;

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

HTML

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

CSS

#footer {
    height: 100px;
    background-color: grey;
}
  • 1

    Is this what you want? -> http://jsfiddle.net/1Lghrq22/1/ in which case only the position: relative; for example

  • 1

    that’s exactly what I want. Thank you

  • @Sergio by the way.. what if I want to add more than one parameter? how do I do?

3 answers

1


For you to work with elements positions, TOP, LEFT, RIGHT, BOTTOM you MUST use the property Position, with Relative, Absolute, Fixed values...

Otherwise you can use the Margin-Top, with a value of 100px.

Change your CSS to:

#footer {
    height: 100px;
    background-color: grey;
    position:relative; // Note aqui a propriedade Position
}
  • why if I pass the position: relative for position: fixed to div desaparece jsfiddle.net/1Lghrq22/1

  • 1

    Why you have to set a size width for the elements.

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 better code reading:

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

Note that now the attribute/value pairs must be between apostrophes or quotation marks, and must be separated by :(two points) and no longer by commas, the comma is now used to separate the attributes you want to manipulate.

0

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

var elemento = document.querySelector("#teste");
elemento.style.backgroundColor = "#D93600";

Browser other questions tagged

You are not signed in. Login or sign up in order to post.