Bones
Bones

Reputation: 1

Change CSS properties via JavaScript

I need to modify some CSS properties via JavaScript. The website I need to work with is based on a CMS and I can only edit body elements to inject code.

I was wondering if there was a way to use JavaScript to modify/override the CSS on-the-fly as the page loads?

At the present time I am looking to modify two properties (but maybe more in the future):

background-image:url(http://mysite.com/img/bg.jpg);
background-attachment: scroll;

I would like them to be changed to the following on the specific page I intend to embed this script on:

background-image:url(http://mysite.com/img/new_bg.jpg);
background-attachment: fixed;

I tried this, but it did not work (remember I can only put this within the body of the page):

<script type="text/javascript">
    document.getElementById("body").style.backgroundImage = 'url(http://mysite.com/img/new_bg.jpg)';
</script>

Any ideas? Thanks.

Upvotes: 0

Views: 116

Answers (1)

SLaks
SLaks

Reputation: 887547

document.getElementById takes an element ID.

Unless you have an element with id="body", your code won't find any element.

You probably want document.body, which always returns the one and only <body> element.

Upvotes: 5

Related Questions