How to: Apply a class to all elements of a specific type on a page

I needed to be able to apply a specific class to all my img tags that were linked to their original size images, so that the full size image would be displayed in a fancybox. This was necessary as the content providers were not too happy about having to add the class name to their anchor tags by hand. The following gets a collection of all the image tags “img” that are inside anchor tags “a” and adds the required class name to their class attribute.

if (document.URL.indexOf(“blog”)>0)
$(“a img”).parent().addClass(“single_image”);
$(“a.single_image”).fancybox({‘hideOnContentClick’: true});

1. As there were issues with the classname being added to images that were not supposed to support the fancybox, the if statement makes sure that the classname and script are only applied to blogposts.
2. $(“a img”).parent() gets the collection of anchor tags. $(“a img”) gets the collection of image tags.
3. .addClass(className) adds the className to the class attribute of the anchors. This happens for all the anchors selected in the previous line.
4. document.getElementsByTagName(“a”)[0].single_image=”; this should be exactly the same as having said $(“a”)[0].removeClass(“single_image”); but for some reason, I couldn’t get that to work. Hence, pure javascript was used to remove the className from the first anchor in the collection. This was necessary as the first anchor was the logo and it was not supposed to be displayed in a fancybox (but, rather, navigate to the homepage)
5. $(“a.backToTop”).removeClass(“single_image”); as above, it was necessary to remove the className from the anchor tag that navigates the user to the top of the page.
6. $(“a.single_image”).fancybox({‘hideOnContentClick’: true}); this attaches the fancybox script to all tags that bear the single_image tag.

The lightbox/fancybox used can be found here.

MGR: the Intelogist

About MGR: the Intelogist

SharePoint Server developer, turned Sitefinity developer, turned Angular developer, turned SharePoint Online consultant, turned Unily consultant, turned O365 consultant... Never a dull moment!

Leave a Reply

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

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> 

This site uses Akismet to reduce spam. Learn how your comment data is processed.