Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically change <div> background-image with javascript

I'm looking for some help writing a javascript snippet that will DYNAMICALLY update a div style= "background-image:url..." to match the a href above it. This is on a portfolio website, so this is a gallery where all the images are live at once. I need the snippet to run through each individual a href and nested div underneath it and have them match, unique to each image (Don't want a page of the same picture 20 times) I'm just starting to learn JS, so I've been struggling with this one. Here's the html.

<a id ="tobematched" href="imgs/galleryphotos/1.jpg">

This href should from above should be copied to the div style url below.

<div id ="matcher" class="img-container" style="background-image: url('imgs/notcorrect/currently.jpg');"></div>
</a>

This is what it looks like as a whole...

<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'm thinking, so far...

function abc() {
    var a = document.getElementById("tobematched").
    var b = document.getElementById("matcher").style.backgroundImage;

                        }

Not sure where to go from here, since I don't know how to grab the href... I think I'm on the right track.

like image 271
tman091 Avatar asked Oct 18 '22 16:10

tman091


1 Answers

You can use a combination of querySelector() and the .href property to get what you need:

var targetDiv = document.querySelector('#matcher');
var url = targetDiv.parentNode.href;
targetDiv.style.backgroundImage = 'url(' + url + ')';

Alternatively you can use:

var url = document.querySelector('#tobematched').href

This second option does not depend on the structure of the document, but causes JS to look through the whole document again.

If you were using jQuery:

var url = $('#tobematched')attr('href');
$('#matcher').css('background-image', 'url(' + url + ')');

Live Example


Edit: As per the further description by OP in the comments, here is the code you actually need:

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 + ')';
}
like image 165
Pabs123 Avatar answered Oct 30 '22 20:10

Pabs123