USING JAVASCRIPT, NO JQUERY Hi all, I know this is a basic one but I am hitting a dead end. I want to change a background image that is in the .css
, not the html
so I cant give it an id
. I managed to remove the image using:
var headerImg = document.getElementById('header').background = 'none';
And tried :
var headerImg = document.getElementById('header').background = 'images/new-header.jpg;
But that did'nt work. I have no idea how to change the Image, and in the dev tools the url does not even change when I try to run my code Any help would be great, Thanks.
You're close. You're just off on the syntax slightly...
document.getElementById("header").style.backgroundImage = "url(images/new-header.jpg)";
It's a style attribute you're changing, so you need .style
and then you use the CSS attribute name, but remove hyphens and camelCase the attribute name, so .backgroundImage
.
Can you try this
var element = document.getElementById('content'); element.style.backgroundImage = "url('https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcSzOpUTzDIq2yutn75PQTLcHhJ06MTZPsV_V-0M918xKUhAqMxE')";
<div> <p>this is unchanged</p> <p id="content">backgroud wiil be cange</p> <div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.