I’m using the Divi theme builder on my site. I’ve placed captions under each of my images in a text block. The captions are all in italics. Could anyone tell me if it’s possible for me add some JavaScript that would automatically recognise the caption lines and apply a CSS class to them? It would be good if this could be automated as it would be very time consuming to manually add the CSS class to each caption.
This is the HTML I’m using:
<div class="dmpro_timeline_item_description">
<p>
<a style="color: inherit;" href="https://path-to-image.jpg">
<img decoding="async" loading="lazy" src="https://path-to-image.jpg" width="300" height="237" alt="" class="wp-image-2179 alignnone size-medium" srcset="https://path-to-image.jpg 300w, https://path-to-image.jpg 1024w, https://path-to-image.jpg 768w, https://path-to-image.jpg 1536w, https://path-to-image.jpg 2048w, https://path-to-image.jpg 15w, https://path-to-image.jpg 1080w, https://path-to-image.jpg 1280w, https://path-to-image.jpg 980w, https://path-to-image.jpg 480w" sizes="(max-width: 300px) 100vw, 300px">
<br>
<em>This is the image caption text.</em>
</a>
</p>
<p>This is where further details go (outside of the caption)</p>
</div>
4
Answers
If your images and captions will always be in the following format:
Then you can do it with CSS:
If you want to actually add a class name to the
<em>
tags, you can do it with jQuery:Just add this to your javascript:
you can use this
this will find images with lazy attribute and add class to second element after img.
Since CSS is read right to left you should always be as concise as possible, in this instance you should use the general sibling selector.
In JavaScript, to apply a class, do the following:
you could then style this as follows:
But at this point, I would say that it is better to handle this entirely in CSS.
Otherwise, you are asking the browser to find all the elements initially (to apply the class to them), and then further processing to style the elements based on the class that you have added. This could be done in one step by CSS.