+ 2
JS changing background with getElementByld
Hi guys! While training getElementByld part - i wanted to change main background with it. No success. Where is mistake? Help pls do it right https://code.sololearn.com/Wpcsn6IZEa5q/#css
5 Antworten
+ 11
Some mistakes I found -
★ You should add an ID attribute to body tag first.
★ There's no need for <script> tags in JS section.
★ It's "getElementById()" not "getElementByld()"
★ There's a problem with the link too I think..Try uploading the image to some free hosting service and copy the link from there (example - imgur)
After doing all this, dont forget to wrap all the Javascript code in a window.onload function. example -
window.onload = function (){
//All JS Code here
}
Pro Tip - You don't have to declare a special variable if you have already assigned "id" to something ... Just do -
body.style.backgroundColor or something.
If your code still doesn't work, feel free to ask ^^
+ 5
1. element.getElementById is used to target id element, there is no element by the id body in your code.
2. script tag is unnecessary(and incorrect in this context) in Javascript tab
3. select the body element with querySelector('body') then use x.style.backgroundImage = 'url(my-image-link-here.jpg')'
4. wrap the entire code in an onload or similar event like.
//javascript code below
this.addEventListener('DOMContentLoaded', boot)
function boot(){
var x = document.querySelector('body')
x.style.backgroundImage = "url(https://images.duckduckgo.com/iu/?u=https%3A%2F%2Fi.ytimg.com%2Fvi%2FkFzBagbox_c%2Fmaxresdefault.jpg&f=1)";
}
+ 4
Max Rubs
The code i and nomeh posted do work i checked them both.
Your code isn't working because after window.onload it's "=" you wrote "."
while in the post you have url(link) in double quotes; your code has it outside of it, fix these issues the code works fine like before...
https://code.sololearn.com/WtYDmWfo814d/?ref=app
+ 1
Just replace your .js file with this:
this.onload = ()=>{
document.body.style.background = "url(https://images.duckduckgo.com/iu/?u=https%3A%2F%2Fi.ytimg.com%2Fvi%2FkFzBagbox_c%2Fmaxresdefault.jpg&f=1')";
}
0
Nikhill, thx but not working
Nomeh Uchenna Gabriel , thx but not working
Lord Krishna - your variant too
still without success
window.onload.function(){
var x = document.getElementById("body");
x.style.backgroundImage = "url(https://sun9-1.userapi.com/c840723/v840723501/7b271/JgmSwCHns3U.jpg)";
}