1

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/

3
  • are you using jquery? Commented Sep 19, 2014 at 11:22
  • I am. I could be using $("sidescrollbtn") instead of document.getElementById("sidescrollbtn") I guess, but that wouldn't make a difference, right? Commented Sep 19, 2014 at 11:24
  • @ViniciusSantana it makes difference. Javascript has DOM object whereas jQuery has jQuery object. if you want to use jquery methods, then you must use jquery object. Commented Sep 19, 2014 at 11:32

5 Answers 5

3

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' });
Sign up to request clarification or add additional context in comments.

1 Comment

@wintermute just getting the answer in there first, I always explain :)
2

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

1 Comment

@NishanthiGrashia, I do not consider making my OR's bold a legitimate edit. If I wanted them bold, I would have made them bold.
1

you can give css using

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

Comments

1

Use HTML DOM

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

Example:

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

Comments

0

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' });

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.