Ethan E Ethan E - 3 years ago 49
Javascript Question

loop through alphabet and add ID to A tags

I have four a tags without an ID wrapped in a div

<div class = "comTabs">
<a></a>
<a></a>
<a></a>
<a></a>
</div>


i would like to name the a tag Ids using a for loop of the letters of the alphabet in descending order

<div class = "comTabs">
<a id = "A"></a>
<a id = "B"></a>
<a id = "C"></a>
<a id = "D"></a>
</div>


here is my JS

for (var i = 0; i < ($('.commTabs a').length); i++) {
var $elem = $('.commTabs > a')[i];


here is where its going wrong, all the A tag IDs are defined as "Z"

for (var letter = 65; letter <= 90; letter++) {
$($elem).each(function(i) {
$(this).attr('id', String.fromCharCode(letter));
});
}}


thanks in advance!

Answer Source

You can do it directly like below using $('.comTabs a').each(function(i){:-

Example:-

$('.comTabs a').each(function(i) {
   $(this).attr('id', String.fromCharCode(65 + i));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class = "comTabs">
  <a>1</a>
  <a>2</a>
  <a>3</a>
  <a>4</a>
</div>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download