Add <a> href to img with appendto

63
October 19, 2021, at 02:40 AM

I'm hoping someone can help.

I have a piece of JavaScript that takes all images on a page and appends them to a newly created div to create a slideshow. I'm now looking to add <a href="#lightbox"> around each <img> so that they can be used to open a lightbox.

This is my code

var txt3 = document.createElement("div"); // Create with DOM
txt3.className = "slider";
$('.pi-gallery').append(txt3); // Append the new elements
$('.pi-gallery img').each(function() {
  $(this).detach().appendTo('.slider');
});
$(function() {
  $('.slider img:gt(0)').hide();
  setInterval(function() {
      $('.slider :first-child').fadeOut()
        .next('img').fadeIn()
        .end().appendTo('.slider');
    },
    3000);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

If someone can offer me some pointers it would be much appreciated.

Answer 1

You can use wrapAll() to wrap the slider div around them all and then wrap() within a loop for the <a>

$('.pi-gallery img').wrapAll('<div class="slider">').each(function() {
  $(this).wrap('<a class="slide" href="#lightbox">')
});
.slider a.slide {
  display: block;
  border: 2px solid red;
  height: 150px;
  width: 150px
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="pi-gallery">
  <img src="https://via.placeholder.com/150?text=one" />
  <img src="https://via.placeholder.com/150?text=two" />
  <img src="https://via.placeholder.com/150?text=three" />
</div>

READ ALSO
How to use database in Heroku

How to use database in Heroku

I am new in web applications and I created first application in djangoI decided to deployment my project in Heroku

22
How to add Admob banner to all the activities in native code using Android Studio?

How to add Admob banner to all the activities in native code using Android Studio?

I started learning mobile development and I am using Android studio to buildI just made my first app, then I added AdMob banner in it

70
How To Prevent \ Showing Up Next To Quotation Marks? [duplicate]

How To Prevent \ Showing Up Next To Quotation Marks? [duplicate]

My script has it so a user will enter in text, it will go into a MariaDB database and then come back out in the screen to simplify itHowever, when a user enters ' or " it will go to the database as \' or \"

71
RFID 8500 TC52 Connection Failed RFID Batch mode in Progress

RFID 8500 TC52 Connection Failed RFID Batch mode in Progress

when i pass data from activity1 to activity2 the data will pass after connect with sdk to zebra 8500 (TC52) getting error with device high beep sound in zebra device

40