Adding a CSS Class to Link Images Using jQuery
I have been working with a new Genesis theme and came across an issue where the featured image link did not possess a class. This may be fine if you don’t need fine control over image links but I previously styled all of my anchor element with a bottom border. This resulted in the featured images (an linked images in general) having an unsightly border. The problem was that the featured image had no class for me to target with CSS. I could easily add a class to the anchor within the content of a post but for featured images, it wasn’t so easy. To fix it, I included a simple line of jQuery in my child theme and styled the class that it added. Here’s a rundown of the functionality and the actual jQuery for you to use.
Add a Class to Anchor Tag with a Child Image
The jQuery below does the following:
- Checks to see if an image
<img src="">has an anchor tag
<a href=""></a>as its parent
- If the image has an anchor as a parent, add a class named image-link to the anchor
How to Add
To add this snippet to your (child) theme, save it to a file named image-link.js inside your “js” directory. Enqueue the script by adding this line to your functions.php (adjust if necessary):
//* Enqueue script to add class to featured image links wp_enqueue_script( 'image-link-class', get_stylesheet_directory_uri() . '/js/image-link.js', array( 'jquery' ), '', true );
This code is great for adding a class to any linked images, including featured images. Just note that it will attach the .image-link class to ALL links within your website if the links contain an image (I don’t think this will be an issue for anyone, though).
thanks for that article. I use Elementor, the Hello Elementor Theme and SIteground.
Which one should I use?
Hope to hear from you soon 🙂