Fall Sale! Code FALL2024 takes 25% OFF our Pro Plugins & Books »
Web Dev + WordPress + Security
Blackhole Pro
Blackhole Pro: Trap bad bots in a virtual black hole.
Related Posts

Vanilla JavaScript: Add Class to Image Links

It seems that for every new web design, I need to add a specific CSS class to linked images. So I can distinguish between regular text links and image links. And then apply styles as desired for each. I’ve tried all sorts of CSS and JavaScript/jQuery tricks over the years, but so far this one is the best..

Of course, “best” is relative. For me, this snippet is great because it’s simple, lightweight, and written in vanilla JavaScript. So there are no dependencies.

Magic Bullet

Here is the magic code, strictly plug-&-play:

window.onload = function() {
	imageLinks();
}

function imageLinks() {
	var anchors = document.querySelectorAll('a');
	Array.prototype.forEach.call(anchors, function(a) {
		var img = a.querySelector('img');
		if (img !== null) {
			a.classList.add('img-link');
		}
	});
}

This snippet does one thing: adds a class named img-link to all links <a> that contain an image <img> element. Simply add the code and done.

After adding this code, any/all image links will include a class named img-link. Here is an example of the HTML output after applying the above snippet:

<a href="/path/to/somewhere/" class="img-link">
	<img src="/path/to/image.png" alt="">
</a>

So now we can add styles specifically to links that contain an image. For example:

.img-link { border: 1px solid gold; }
.img-link img { border: none; }

Let me know if you can find any way to improve this “magic bullet” vanilla JavaScript technique. Or maybe now it can be done with simple CSS..?

About the Author
Jeff Starr = Creative thinker. Passionate about free and open Web.
GA Pro: Add Google Analytics to WordPress like a pro.
Welcome
Perishable Press is operated by Jeff Starr, a professional web developer and book author with two decades of experience. Here you will find posts about web development, WordPress, security, and more »
.htaccess made easy: Improve site performance and security.
Thoughts
I disabled AI in Google search results. It was making me lazy.
Went out walking today and soaked up some sunshine. It felt good.
I have an original box/packaging for 2010 iMac if anyone wants it free let me know.
Always ask AI to cite its sources. Also: “The Web” is not a valid answer.
All free plugins updated and ready for WP 6.6 dropping next week. Pro plugin updates in the works also complete :)
99% of video thumbnail/previews are pure cringe. Goofy faces = Clickbait.
RIP ICQ
Newsletter
Get news, updates, deals & tips via email.
Email kept private. Easy unsubscribe anytime.