0

I've successfully managed to loop through the desired page elements and add a class name to each with an increasing number to easily identify them later:

var elNum = 1; 
var elName = 'banner';

$.each($('div'), function(i, val) { 
  $(this).addClass(elName + elNum++);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
<div>8</div>
<div>9</div>
<div>10</div>
<div>11</div>

However what I can't figure out is how to make sure the increasing numbers being added from 1-9 have a zero before the number (01-09) so it's added to the class (banner01 - banner09).

I believe it would be something like:

if(elNum.toString().length < 2) {
  elNum = ('0' + elNum);
}

However I can't figure out how I would do this for the ++ increments being looped through when building the structure of the class to add. Help would be appreciated with getting this working.

Chobbit
  • 461
  • 4
  • 14
  • 1
    `if(elNum.toString().length < 2)` so `if(elnum<10)` ? (given it will always be >=0 (otherwise you'd get `"0-1"` for negatives)) – freedomn-m Apr 13 '22 at 08:12
  • 1
    If you don't want to use a pre-existing padStart, then just split your code into multiple lines - ie do the `++` first then append it. Your code doesn't *have* to be on a single line. `elnum++;$(this).addClass(elName + (elNum<10?"0":"") + elNum);` – freedomn-m Apr 13 '22 at 08:14

1 Answers1

1

You can use padStart function from String like:

elNum = elNum.toString().padStart(2, '0')

Thus

$(this).addClass(elName + (elNum++).toString().padStart(2, '0'));

should do the trick. However, you even do not need the elNum:

$(this).addClass(elName + (i+1).toString().padStart(2, '0'));

const elName = 'banner';

$.each($('div'), function(i, val) { 
  $(this).addClass(elName + (i+1).toString().padStart(2, '0'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
<div>7</div>
<div>8</div>
<div>9</div>
<div>10</div>
<div>11</div>
edi
  • 917
  • 7
  • 17