Search code examples
javascripthtmlcsswebkitgradient

Modify background: webkit-gradient with javascript


This should be fairly simple. All I need to do is pass a new block of parameters to my body css tag webkit gradient with a javascript function that gets called from a link. Here's what I tried (among 200 other things):

CSS

body
{
    -webkit-text-size-adjust:100%;
    font-size:100%;
    color:#444;
    position:relative;
    background: -webkit-linear-gradient(top, #154d9e, #b8d8e4);
}

Javascript

<script>
function changeBack()
{
    document.getElementsByTagName("body").style.background="-webkit-linear-gradient(top, #fff, #000)";
    document.body.style.background="-webkit-linear-gradient(top, #fff, #000)";
}
</script>

Neither of those two lines work. What gives?


Solution

  • This doesn't work because document.getElementsByTagName("body") returns an array of elements. You need to specify which element it is. There is only one body tag on a page so this should work:

    document.getElementsByTagName("body")[0].style.background="-webkit-linear-gradient(top, #fff, #000)";