user13286 user13286 - 2 months ago 13
HTML Question

Appending to a ul before an anchor tag

I am building a year list dynamically and I am truncating the list and displaying a "show more" and a "show less" link after the list of years. If I

append
the years to the
ul
, the years come after the "show more/less" links, and if I
prepend
the years, they show before the "show more/less" links but are in reverse order.

Is there a way for me to append the years to the ul but to append them, in chronological order, before the "show more/less" links?



$(function() {
$('.years-append').append('<li><a href="#">2014</a></li>');
$('.years-append').append('<li><a href="#">2015</a></li>');
$('.years-append').append('<li><a href="#">2016</a></li>');
$('.years-append').append('<li><a href="#">2017</a></li>');

$('.years-prepend').prepend('<li><a href="#">2014</a></li>');
$('.years-prepend').prepend('<li><a href="#">2015</a></li>');
$('.years-prepend').prepend('<li><a href="#">2016</a></li>');
$('.years-prepend').prepend('<li><a href="#">2017</a></li>');
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Appending - Years are in correct order, but more/less links come BEFORE years</h2>
<ul class="years-append">
<a class="btn-more" href="#"><span>+</span> More</a>
<a class="btn-less" href="#"><span>-</span> Less</a>
</ul>

<h2>Prepending - more/less links come AFTER years, but years are in reverse order</h2>
<ul class="years-prepend">
<!-- These links should come after the list of years, years should be in chronological order -->
<a class="btn-more" href="#"><span>+</span> More</a>
<a class="btn-less" href="#"><span>-</span> Less</a>
</ul>





Sorry if the wording is confusing, let me know if I need to clarify more.

Answer

Why not changing the HTML? It's the easiest way to achieve what you want. And your HTML is not valid by the way. It's not valid to have <a> directly within a <ul>

HTML:

<div>
  <ul class="years-append"></ul>
  <a class="btn-more" href="#"><span>+</span> More</a>
  <a class="btn-less" href="#"><span>-</span> Less</a>
</div>

JavaScript (untouched):

$(function() {
  $('.years-append').append('<li><a href="#">2014</a></li>');
  $('.years-append').append('<li><a href="#">2015</a></li>');  
  $('.years-append').append('<li><a href="#">2016</a></li>');  
  $('.years-append').append('<li><a href="#">2017</a></li>');
});

Explanation: Before you start scripting and styling you should try to bring the HTML in a logical order. In this case we mark the list and the buttons to belong together by setting them into a <div>. As the list should show up before the buttons, it's also in the HTML like that.

Fiddle: https://jsfiddle.net/8nz3pwtk/

Comments