Javascript: how can i add data field to all the links in a HTML page

I am having a html page where i have to add data-fancybox=”gallery” to all the links in a page to display a image in a fancybox.

right now i am adding manually to all the links in each page.

how can i add automatically data-fancybox=”gallery” to all the links through javascript/Jquery?

Example:

<a data-fancybox="gallery" href="https://example.com/Capture.JPG" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" data-original-height="621" data-original-width="603" height="640" src="https://example.com/Capture.JPG" width="620" /></a>

Answer

Just use JQuery to loop through each <a> element and add a data attribute like this:

$("a").each(function ()
{
    $(this).attr('data-fancybox', 'gallery');
});

EDIT

If you want to add it only to certain <a> elements (like inside a container) look at this example:

(this adds the fancybox data-attribute only to the elements which are inside the .do-add-fancybox container)

$(".do-add-fancybox a").each(function() {
  $(this).attr('data-fancybox', 'gallery');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body>
  <div class="do-not-add-fancybox">
    <p>
      Hello World
    </p>
    <a href="Something">test</a>
  </div>

  <div class="do-add-fancybox">
    <p>
      Hello World, 2
    </p>
    <a href="my Link">test</a>
    <a href="my Link2">test</a>
    <a href="my Link3">test</a>
    <a href="my Link4">test</a>
    <a href="my Link5">test</a>
    <a href="my Link6">test</a>
  </div>
</body>

Leave a Reply

Your email address will not be published. Required fields are marked *