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">

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>

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){:-


$('.comTabs a').each(function(i) {
   $(this).attr('id', String.fromCharCode(65 + i));
<script src=""></script>
<div class = "comTabs">

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