Do I need to repeat `<li>` every time? Is there a way to use a loop?

Is there any way to not repeat yourself when representing several list elements? Or is it standard practice to have several <li> tags among <ul> or <ol> tags even if we represent, for example, a dozen elements?

I like this question, i think this is a good question. But there is no simple answer.

Lets look at a simple example:

https://jsbin.com/fojitexiya/edit?html,css,output

i made a simple top navigation menu. Could we eliminate the duplicate <li></li> elements? Yes, we could using a loop:

https://jsbin.com/hakifucome/edit?html,css,js,output

Don’t know if you learned JS yet, but as you can see, now we have a lot more code. Yes, we don’t have any “duplicate code”, but the abstraction needed this can hardly be justified.

Sure, there are cases where loop are justified, look at this page:

https://discuss.codecademy.com/latest

its part of the codecademy forum, you can say with almost absolute certainty that a loop of some kind is used to render each topic in this list overview. So there certainly are plenty of cases where a loop is fully justified.

I hope this shows why there isn’t one definitive answer :slight_smile:

1 Like

I don’t know much about JS, but I think I understand that you created a loop in a JS file ‘attached’ to the html file in https://jsbin.com/hakifucome/edit?html,css,js,output .

I guess that, inside this loop, if you wanted to add more elements to the list, you would only need to add them following " ‘contact’ " in the first line of JS code:

Old:

const navItems = [‘home’, ‘about’, ‘contact’]

New:

const navItems = [‘home’, ‘about’, ‘contact’, ‘forum’]

I hope I got it right. Thank you for your time, stetim94. I really appreciate it. :slightly_smiling_face:

exactly. But that is the other side of the story. If you wanted a page where users could add or remove elements from the list, we could use JS to do this. So then the additional complexity/abstraction is justified.

There are always multiple factors (flexibility, maintainability, cost, efficiency) to consider

1 Like

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