'jQuery - ++ Increments but with a 0 for single digit numbers [duplicate]
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.
Solution 1:[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>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
