I'm attempting to write a script that will take the 'img src' and copy it to an 'a href'. The trick is that this page I'm working on is a photo gallery, with multiple images on the page that this script needs to work on. This needs to happen as soon as the page is loaded. Here's my HTML:
<!-- Album row 1 -->
<div class="col-md-6 col-sm-6 album">
<a class = "img-container-alt" href="**this_is_where_the_imgsrc_below/will_end_up.jpg**" data-gallery>
<div class="photo-overlay"></div>
<figure>
<img class="img-responsive album-img" src="**this_is_what_/i_would_like_copied_above.jpg**" alt="">
</figure>
</a>
</div>
The trick is, like I said, getting it to run through multiple divs that are identical to this one and dynamically grabbing each img src
and copying it to the a href
above it within the div
. Here's what JS I've done so far:
<!-- Script -->
<script type="text/javascript">
window.onload = function abc() {
console.log('hello')
var copyto = document.querySelectorAll('.img-container-alt');
var copy = document.querySelectorAll('album-img');
for (var i = 0; i < copyto.length; i++) {
var url = copy[i].src;
copyto[i].href = url;
}
}
</script>
When I run that, I get this error:
Uncaught TypeError: Cannot read property 'src' of undefined, which is referring to the var url = copy[i].src;
. I'm not sure if my script is the best option for what I'm trying to do, but I'm stumped now. I'm relatively new to JS, so any help would be appreciated. Thanks in advance. If I need to clarify anything, please let me know.
As pointed out by @Ian Devlin and @t.niese, I had two problems that needed to be fixed. First, my var url = copy[i].src;
was undefined. Why? Because I was missing a .
in my var copy = document.querySelectorAll('.album-img');
where album-img
was. Secondly, I couldn't grab the src
in the var url = copy[i].src;
, so we switched that to copy[i].getAttribute("src")
and it worked perfectly.
Here's the working script now....
<!-- Script -->
<script type="text/javascript">
window.onload = function abc() {
var copyto = document.querySelectorAll('.img-container-alt');
var copy = document.querySelectorAll('.album-img');
for (var i = 0; i < copyto.length; i++) {
var url = copy[i].getAttribute("src");
copyto[i].href = url;
}
}
Thanks for the help guys.