Home > database >  Is there a way to show the count of elements in an HTML element?
Is there a way to show the count of elements in an HTML element?

Time:05-17

I have following dynamically created html markup:

<div >
    <div ><h2 >Tips & tricks</h2><img src="..."></div>
    <div ><h2 >About us</h2><img src="..."></div>
    <div ><h2 >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.

CodePudding user response:

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 >
  <div >
    <h2 >Tips &amp; tricks</h2>
    <img src="...">
  </div>
  <div >
    <h2 >About us</h2>
    <img src="...">
  </div>
  <div >
    <h2 >Start up</h2>
    <img src="...">
  </div>
</div>

CodePudding user response:

Declare a counter (that equals the number of .tmb) outside of the function:

let cnt = $('.tmb').length;

Then use .each() and decrement the counter on each iteration:

$('.tmb').each(function() {
  $(this).prepend(`<p class='podcast-episode'>Episode ${cnt--}</p>`);
});

let cnt = $('.tmb').length;

$('.tmb').each(function() {
  $(this).prepend(`<p class='podcast-episode'>Episode ${cnt--}</p>`);
});
<div >
    <div ><h2 >Tips & tricks</h2><img src="..."></div>
    <div ><h2 >About us</h2><img src="..."></div>
    <div ><h2 >Start up</h2><img src="..."></div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

  • Related