TriSTaR TriSTaR - 19 days ago 5
HTML Question

How get miscellaneous images src jQuery

Good day, I want to use Lightbox in my site and i want to change img view with lightbox...



$('img').wrap('<a href="#" data-lightbox="lightbox" class="lightbox-link"></a>');
$('.lightbox-link').attr({'href': $('img').attr('src')});

<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<title>Lightbox Example</title>
<link rel="stylesheet" href="http://lokeshdhakar.com/projects/lightbox2/css/lightbox.css">
</head>
<body>
<div>
<img src="http://lokeshdhakar.com/projects/lightbox2/images/thumb-3.jpg" alt=""/>
<img src="http://lokeshdhakar.com/projects/lightbox2/images/thumb-4.jpg" alt="" />
<img src="http://lokeshdhakar.com/projects/lightbox2/images/thumb-5.jpg" alt="" />
</div>

<script src="http://lokeshdhakar.com/projects/lightbox2/js/lightbox-plus-jquery.min.js"></script>

</body>
</html>





The problem is when I get img
src
with jQuery his get only first and one
src
and put him for all links attribute
href
... How i can get all
src
and put in the appropriate links?

Answer

Use a each loop to loop each img and wrap each image individually with the current image src

$('img').each(function() {
  $(this).wrap('<a href="' + $(this).attr('src') + '" data-lightbox="lightbox" class="lightbox-link"></a>');
})
<!DOCTYPE html>
<html lang="en-us">

<head>
  <meta charset="utf-8">
  <title>Lightbox Example</title>
  <link rel="stylesheet" href="http://lokeshdhakar.com/projects/lightbox2/css/lightbox.css">
</head>

<body>
  <div>
    <img src="http://lokeshdhakar.com/projects/lightbox2/images/thumb-3.jpg" alt="" />
    <img src="http://lokeshdhakar.com/projects/lightbox2/images/thumb-4.jpg" alt="" />
    <img src="http://lokeshdhakar.com/projects/lightbox2/images/thumb-5.jpg" alt="" />
  </div>

  <script src="http://lokeshdhakar.com/projects/lightbox2/js/lightbox-plus-jquery.min.js"></script>

</body>

</html>