I'm trying to open an image on click with a simple JQuery.
I'm building on the code provided here: https://stackoverflow.com/questions/54040130/is-there-a-css-option-that-links-an-html-image-to-itself#:~:text=Nice%20idea%2C%20but,Expand%20snippet
Everything works fine. However, I want to add a detail: the image should open only if the parent doesn't have an already defined href attribute. Differently the original href should open instead. Now all the parent of an image get overwritten. How can I avoid this?
On the code below, the first image should open itself. The second one should open the original href. I want to avoid to use two different classes for the two images. It should be possible to override the href only if undefined using JQuery. How can I do?
index.html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="script.js"></script>
<a><img src="image2.jpg" class="clickable"></a>
<a href="https://stackoverflow.com/"><img src="image1.jpg" class="clickable"></a>
script.js
$( document ).ready(function() {
$("img").each(function(){
var imgUrl = $(this).attr('src');
$(this).parent().attr('href', imgUrl);
});
});
For some reason this works: ```HTML
``` This doesn't: ```HTML
– prb Sep 02 '22 at 00:36