Apply class to every paragraph that holds image?

When adding an image to a page or post, WordPress is automatically adding a paragraph tag <p> as parent holding the image. Like so:

<p><img src="https://wordpress.stackexchange.com/questions/16033/my-image.jpg" alt=""></p>

Since there is no parent selector in CSS I’d love to find a solution to apply a specific classname to those paragraphs holding an actual image. The example above would thus result in:

<p class="my-class"><img src="https://wordpress.stackexchange.com/questions/16033/my-image.jpg" alt=""></p>

Any idea if I can use add_filter() to apply a classname to each p that holds an image?

4 s
4

You could use jQuery if you don’t mind to rely on JavaScript for adding the class.

$(document).ready(function() {
    $('p:has(img)').addClass('image');
});

Update: the .has() method is probably faster, see this jsperf.com test.

$(document).ready(function() {
    $('p').has('img').addClass('image');
});

Leave a Comment