Vinicius Santana
Vinicius Santana

Reputation: 4106

How to change a css property with javascript?

I'm trying to change the margin-top css element of a div using javascript but its not working. Here is my code:

document.getElementById("sidescrollbtn").css({'margin-top':'70px'});

Any ideas?

Fiddle: http://jsfiddle.net/vinicius5581/2y63xnxa/5/

Upvotes: 1

Views: 585

Answers (5)

James Hill
James Hill

Reputation: 61872

You can do it a several ways:

// Reference property name
document.getElementById("sidescrollbtn").style.marginTop = '70px';

OR

// Use setAttribute method
document.getElementById("sidescrollbtn").setAttribute("style", "margin-top: 70px");

OR

// Use jquery .css()
$('#sidescrollbtn').css({ 'margin-top': '70px' });

Additional Information

Upvotes: 2

myaseedk
myaseedk

Reputation: 1978

In the JSFiddle you created, this will work if you replace the line of code having issue with the below line of code.

document.getElementById("sidescrollbtn").style.marginTop = '70px';

You can also apply style by using jQuery as below

$('#sidescrollbtn').css({ 'margin-top': '70px' });

Upvotes: 0

devst3r
devst3r

Reputation: 562

Use HTML DOM

document.getElementById(id).style.property=new style

Example:

<script>
document.getElementById("p2").style.color = "blue";
</script>

Upvotes: 1

Darshak Shekhda
Darshak Shekhda

Reputation: 646

you can give css using

document.getElementById("p2").style.color = "blue";

Upvotes: 1

Joe
Joe

Reputation: 15812

In vanilla JS, just set .style.{camelCasedProperty} = 'value';

document.getElementById("sidescrollbtn").style.marginTop = '70px';

You can also do it with jQuery using the object notation you tried:

$('#sidescrollbtn').css({ 'margin-top': '70px' });

Upvotes: 3

Related Questions