Richard Richard - 1 month ago 7
HTML Question

Valid HTML structure for list of links with "show more" section?

I have a list of links on my HTML page. I want to show 3 links by default, then have a "show more" link that the user can click on to reveal the full list. My question is about the best semantic HTML structure for this.

This is my HTML right now:

<ul>
<li>my link</li>
<li>my link</li>
<li>my link</li>
<li><a href="#" id="more">show more</a></li>
<span id="showmore">
<li>my link</li>
<li>my link</li>
...
</span>
</ul>


And I have some Javascript to hide the contents of
#showmore
initially, and to handle clicks on
#more
to show the rest of the list.

$("#showmore").hide();
$("#more").on('click', function(e) {
e.preventDefault();
$("#showmore").show();
});


However, my question is, how do I make this valid HTML and also make it sensible, compact HTML?

I guess I could do the following:

<ul>
<li>my link</li>
<li>my link</li>
<li>my link</li>
<li><a href="#" id="more">show more</a></li>
<li class="more">my link</li>
<li class="more">my link</li>
...
</ul>


But it doesn't seem very efficient - I have a lot of links.

Also, it seems odd having the "show more" link as a list element, which logically it isn't, but I'm not sure where else it should go.

Answer

You don't need any special structure for that.

Just add class .brief to your container and this style rule:

.list-container.brief li:nth-child(n+4) { display:none; }
<div class="list-container brief">
      <ul>
        <li>my link 1</li>
        <li>my link 2</li>
        <li>my link 3</li>
        <li>my link 4</li>
        <li>my link 5</li>
      </ul>
</div>

and when you need to show full list remove that .brief class - it will show all items.

Comments