I'm having difficulty updating the background of a div in both javascript and jquery.
html
<div id="images">
<img class="mypics" src="kitty.png" style="display:none"></div>
<img class="mypics" src="doggy.png" style="display:none"></div>
<img class="mypics" src="mouse.png" style="display:none"></div>
</div>
javascript / jquery
picArray = document.getElementsByClassName("mypics");
$('#images').css('background-image', 'url("' picArray [0].src '")');
CodePudding user response:
Try below syntax
$('#images').css('background-image', 'url(' picArray[0].src ')');
CodePudding user response:
Do you want to change single div backgtound? Use querySelector
const picArray = document.querySelector(".mypics");
$(picArray).css('background-image', 'url("' picArray [0].src '")');
Multi div?
getElementsByClassName
is HTMLCollection
const picArray = document.getElementsByClassName("mypics");
picArray.forEach(pic => {
$(pic).css('background-image', 'url("' picArray [0].src '")');
});
Also you can use #images
children
consr images = document.getElementById("images").children;
Array.from(images).forEach(pic => {
$(pic).css('background-image', 'url("' picArray [0].src '")');
});
Notice: Use Array.from
because children
is array-like