Ira G
Ira G

Reputation: 131

Adding an attribute to a WRAP inserted HREF

I am fairly inexperienced with JQuery, but have been holding my own thanks to snippets, the API docs, and this group.

To keep my site smaller and reduce bad links, I have been using a class "hrefme" in img tags which calls a JQUERY routine which surrounds the IMG tag with A HREF tag so that a larger version can be shown - so:

 <img src="x.jpg" class="hrefme">

gets turned into

<a href="x.jpg"><img src="x.jpg"></a> 

I would like to modify the code to also insert a "data-fancybox" into the HREF tage so that it would read

<a data-fancybox="" href="x.jpg"> 

but I cannot figure out how.

My code is here - if anyone could take pity and help I would appreciate it.

jQuery(document).ready(function($) {
  $("img.hrefme").each(function() {
    var $this = $(this);
    var src = $this.attr('src');
    $this.addClass('image');
    var a = $('<a/>').attr('href', src);
    $this.wrap(a);
  });
});

Thanks!

Upvotes: 0

Views: 19

Answers (1)

Mohamed-Yousef
Mohamed-Yousef

Reputation: 24001

You can add attributes like this

var a = $('<a/>').attr({
      "href" : src,
      "data-fancybox" : "something"
    });

jQuery(document).ready(function($) {
  $("img.hrefme").each(function() {
    var $this = $(this);
    var src = $this.attr('src');
    $this.addClass('image');
    var a = $('<a/>').attr({
      "href" : src,
      "data-fancybox" : "something"
    });
    $this.wrap(a);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<img src="https://via.placeholder.com/150" class="hrefme">

Upvotes: 1

Related Questions