Dynamically change the background image of a <div> using javascript
I need help writing a javascript snippet that will DYNAMICALLY update the div style = "background-image: url ..." to match the href above it. This is on the portfolio website, so this is a gallery in which all the images live at once. I need a fragment to run through each separate a hrefand nested divunder it and have their correspondence unique to each image (you do not want the page of the same image 20 times) I am just starting to learn JS, so I struggled with this. Here is the html.
<a id ="tobematched" href="imgs/galleryphotos/1.jpg">
This href should be copied from above to the div style URL below.
<div id ="matcher" class="img-container" style="background-image: url('imgs/notcorrect/currently.jpg');"></div>
</a>
This is how it looks in general ...
<a id ="tobematched" href="imgs/galleryphotos/1.jpg">
<div id ="matcher" class="img-container" style="background-image: url('imgs/notcorrect/currently.jpg');"></div>
</a>
Any help would be greatly appreciated!
This is what I think so far ...
function abc() {
var a = document.getElementById("tobematched").
var b = document.getElementById("matcher").style.backgroundImage;
}
, , , href... , .
querySelector() .href, , :
var targetDiv = document.querySelector('#matcher');
var url = targetDiv.parentNode.href;
targetDiv.style.backgroundImage = 'url(' + url + ')';
:
var url = document.querySelector('#tobematched').href
, JS .
jQuery:
var url = $('#tobematched')attr('href');
$('#matcher').css('background-image', 'url(' + url + ')');
: OP , , :
var targetDivs = document.querySelectorAll('.img-container');
for (var i = 0; i < targetDivs.length; i++) {
var url = targetDivs[i].parentNode.href;
targetDivs[i].style.backgroundImage = 'url(' + url + ')';
}