Select Anchor Link that Contains Image in jQuery

Although CSS is very powerful, it sometimes lacks support in certain areas. For example, you cannot select an a parent that contains a specific child. This is where jQuery comes to the rescue.

Consider this example; we have a CSS rule that adds a border-bottom to all links.

a {
    border-bottom: 1px solid rgba(0, 0, 0, 0.6);
}

Now consider what would happen when we have an image link. It will add the border to the bottom of the image! And we don’t want that.

<a href="http://website.com/">
    <img src="img/awesome.jpg" alt="Some awesome image" />
</a>

To select any anchor link that contains an image, we can use jQuery like this.

$(document).ready(function(){
    $("img").parent("a").addClass("contains-img");
});

Now we can simply go to our CSS, and add this rule.

.contains-img {
    border-bottom: 0;
}

This snippet can be used in a number of ways, not just for selecting an anchor link that contains an image. But any parent with a specific child element of your choosing!

Post a Comment

To post code, use the code tag with a class language-*
Examples: code class="language-markup"code class="language-css"