Semantics when rendering dynamic lists of links
Is a list still a list if it only has one item? Another way to think about dynamic lists in the frontend.
When using tools such as a content management systems like Umbraco, one common piece of functionality to see are lists of links.
Another thing I often spot when working on website are when those lists only have a single item in, we still get given a list.
For example, this is how you may decide to render out a Multi Url Picker data type in Umbraco. For those who don't use Umbraco, the property lets you add one or more links to you content.
The following code example is taken from their documentation.
@using Umbraco.Cms.Core.Models
@{
var links = Model.Value<IEnumerable<Link>>("footerLinks");
if (links.Any())
{
<ul class="your-list-styles-go-here">
@foreach (var link in links)
{
<li><a href="@link.Url" target="@link.Target">@link.Name</a></li>
}
</ul>
}
}
One thing the above doesn't take into acount though is what if you only decide to add a single link? It would end up creating something like this.
<ul class="your-list-styles-go-here">
<li><a href="#" target="_blank">Some interesting website</a></li>
</ul>
From a semantics perspective, you're telling the browser to expect a list, but then only providing a single item.
To me this feels a little odd. Instead why not add a little check so that if there is only a single link in the list, we remove the `<ul>` (unordered list) semantics from the HTML, like so.
@using Umbraco.Cms.Core.Models
@{
var links = Model.Value<IEnumerable<Link>>("footerLinks");
if (links.Any())
{
if (links.Count() > 1)
{
<ul class="your-list-styles-go-here">
@foreach (var link in links)
{
<li><a href="@link.Url" target="@link.Target">@link.Name</a></li>
}
</ul>
}
else
{
@* As we only have a single link, we can use a div instead of a list. *@
<div class="your-list-styles-go-here">
@foreach (var link in links)
{
<div><a href="@link.Url" target="@link.Target">@link.Name</a></div>
}
</div>
}
}
}
This then changes the outputted code to something like this.
<div class="your-list-styles-go-here">
<div><a href="#" target="_blank">Some interesting website</a></div>
</div>
It's a fairly small change that can be made to visually the same as the list element, but what it does is removes a potentially unnessesary reference to a list, which in turn can improve the experience for people visiting your website that may rely on assistive technologies.
For example, when using the `<ul>` element, the screen reader NVDA will read out
"List with one item Some interesting website Link"
With our updated code, it will shorten it to the following
"Some interesting website Link"
It's a subtle difference, but I think it makes it a little friendlier. Anyway, this was one of those small random thoughts I had a while back and have been meaning to do a small write up about for some time. Hope you have found this useful.