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:Javascript: Change <a href> to match <img src> multiple times on a page
<!-- 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.
Итак, вместо 'var copy = document.queryselectorall ('album-img')', вы предлагаете 'var copy = document.getAttribute (" src ")', правильно? Кажется, что это не работает, поскольку '.getAttribute' не является функцией. – tman091
Нет, я имею в виду try 'copy [i] .getAttribute (" src ")' в вашем цикле. Но то, что t.niese говорит ниже, также является правильным. Всегда отлаживайте свой код и смотрите, где значение равно null. –
Ваш 'copy [i] .getAttribut (" src ")' был именно тем, что мне нужно. ТАКЖЕ, @ t.niese решил мою другую проблему, что у меня было (отсутствует «.» В моем альбоме-img ... gosh.) Двое из вас помогли мне, и вместе ваши ответы решили мою проблему. Спасибо, тонны парней. Я буду ссылаться на это в будущем. – tman091