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?


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


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

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


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=""></script>

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

  <div class="do-add-fancybox">
      Hello World, 2
    <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>

Leave a Reply

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