Using "Closest" With JQuery

I got the chance to play with some jquery selectors recently. I found a useful function called “closest” that will traverse up through all parent elements of an element until it finds a parent that matches the selector.

One real world application of this function is in the blog world where you have many blog posts that have common elements, like images. How about if you want to specify the title attribute of each of those images as the title of their respective blog posts? Well the “closest” function comes in handy here.

So how do we use this? Here’s an example where we have two “blog posts” where the containing divs have the same class. And in each blog post is an image where we want to set the title attribute to the title of each post.

The HTML…

Post 1

Post 2

Some quick CSS to make it look nice… .closestPost { width: 100%; background-color: rgba(255,255,255,.5); text-align: center; } .closestPost > img { height: 200px; width: 200px; margin: 5px; } .closestPost > h2 { color: black; }

Then we use jquery to select the inner images and then the “closest” function to grab the title of each post and plug it into each image’s title attribute… $(‘div.closestPost > img’).each(function() { var title = $(this).closest(‘div’).find(‘h2’).html(); $(this).attr(‘title’, title); });

And here’s how it looks all put together. Notice that when you hover over the images, they display their respective post’s title…

Post 1

Post 2

.closestPost { width: 100%; background-color: rgba(255,255,255,.5); text-align: center; } .closestPost > img { height: 200px; width: 200px; margin: 5px; } .closestPost > h2 { color: black; } $(‘div.closestPost > img’).each(function() { var title = $(this).closest(‘div’).find(‘h2’).html(); $(this).attr(‘title’, title); });

Advertisements