Adding class to first dynamically created li tag

I am creating <li> elements as shown below from some JSON response. The problem with the following creation is that I have fixed and same number of bootstrap classes defined for each <li> element.

If I want to add the class="active" in the first <li> tag and not in the remaining tags so that the declaration would look like the following for the first list element :
<li role="presentation" class = "active" >.

Is it possible to achive this?

for (var key in jsonData) {
           if (jsonData.hasOwnProperty(key)) {
             console.log(key + " -> " + jsonData[key].textName);
                
    $('#tabs').append('<li role="presentation" ><a data-toggle="tab" id="tab_'+jsonData[key].textName+'" href="#panel_'+jsonData[key].textName+'">'+jsonData[key].textName+'<span id="count_'+jsonData[key].textName+'" class="countLabel"></span></a></li>');
                                   
        }
                        
    }

After the for loop, add the following:

$('#tabs').first().addClass('active');

HTH,

^ _ ^

Thanks. So adding it like this won’t execute the line $('#tabs').first().addClass('active'); after first iteration?

for (var key in jsonData) {
           if (jsonData.hasOwnProperty(key)) {
             console.log(key + " -> " + jsonData[key].textName);
     $('#tabs').first().addClass('active');           
    $('#tabs').append('<li role="presentation" ><a data-toggle="tab" id="tab_'+jsonData[key].textName+'" href="#panel_'+jsonData[key].textName+'">'+jsonData[key].textName+'<span id="count_'+jsonData[key].textName+'" class="countLabel"></span></a></li>');
                                   
        }
                        
    }

That will not work. That will add the active class to the first li over and over. Place my suggestion AFTER the for loop, so that it will take the first li of #tabs and apply the active class only to that. (That is what you requested, right?)

https://api.jquery.com/first/

V/r,

^ _ ^

Yes, I only want it in the first li tag and not on others. So I will do something like this then:

for (var key in jsonData) {
$(‘#tabs’).first().addClass(‘active’);
if (jsonData.hasOwnProperty(key)) {
console.log(key + " → " + jsonData[key].textName);

$('#tabs').append('<li role="presentation" ><a data-toggle="tab" id="tab_'+jsonData[key].textName+'" href="#panel_'+jsonData[key].textName+'">'+jsonData[key].textName+'<span id="count_'+jsonData[key].textName+'" class="countLabel"></span></a></li>');
                               
    }
                    
}

No. You place it AFTER the WHOLE for loop.

for(key in jsonData){
 your code
} // end of for loop
$('#tabs').first().addClass('active');

HTH,

^ _ ^

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.