I have following dynamically created html markup:
<div class="container">
<div class="tmb"><h2 class="tmb-title">Tips & tricks</h2><img src="..."></div>
<div class="tmb"><h2 class="tmb-title">About us</h2><img src="..."></div>
<div class="tmb"><h2 class="tmb-title">Start up</h2><img src="..."></div>
</div>
I wanted to add a subtitle before each .tmb-title. So I added following jQuery:
$("<p class='podcast-episode'>Episode 1</p>").insertBefore(".tmb-title");
This adds the subtitle ‘Episode 1’ before each .tmb-title, which is what I wanted to achieve.
Now I wanted to change the number in my .podcast-episode subtitle equally to the number of the element starting from the last element. Like the block with the ‘Start up’ title gets the subtitle ‘Episode 1’, ‘About us’ gets the subtitle ‘Episode 2’ and so on..
I tried this:
$count = jQuery(".tmb").size() - 1;
$(".tmb:nth-last-child("+$count+") .podcast-aflevering").text(function(i,txt) {return txt.replace(/\d+/,$count);});
This does the trick for the ‘Tips & tricks’ block, the subtitle is now ‘Episode 3’ but for ‘About us’ it’s still ‘Episode 1’.
If the question is not clear, I’m happy to add the HTML-markup I want to achieve.
>Solution :
Firstly, note that size()
has been deprecated and removed from the latest versions of jQuery. Use the length
property instead, and also update the version of jQuery you’re using. The latest is 3.6.0.
Regarding your issue, to do what you need use length
to determine how many .tmb-title
elements there are then loop through them subtracting the index of the current element in the collection from the total as you go:
jQuery($ => {
let podcastCount = $('.tmb-title').length;
$('.tmb-title').each((i, el) => $(el).before(`<p class='podcast-episode'>Episode ${podcastCount - i}</p>`));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="container">
<div class="tmb">
<h2 class="tmb-title">Tips & tricks</h2>
<img src="...">
</div>
<div class="tmb">
<h2 class="tmb-title">About us</h2>
<img src="...">
</div>
<div class="tmb">
<h2 class="tmb-title">Start up</h2>
<img src="...">
</div>
</div>