0

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.

2
  • This may help: stackoverflow.com/questions/2750710/… Commented Sep 9, 2013 at 2:40
  • I want to do this with pure JavaScript. The link you shared is using JQuery. Commented Sep 9, 2013 at 3:47

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

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.