This is my jQuery script so far:
$(document).ready(function() {
var table = $('#reagent').DataTable();
var alphabet = $('<nav aria-label="Page navigation" id="alphanav">');
$('<li class="clear active" /><a href="#">')
.data('letter', '')
.html('None')
.appendTo(alphabet);
for (var i = 0; i < 26; i++) {
var letter = String.fromCharCode(65 + i);
$('<li/>')
.data('letter', letter)
.html('<a href="#/">' + letter + '</a>')
.appendTo(alphabet);
}
alphabet.insertBefore(table.table().container());
alphabet.on('click', 'li', function() {
alphabet.find('.active').removeClass('active');
$(this).addClass('active');
_alphabetSearch = $(this).data('letter');
table.draw();
});
});
From that I have a list like this:
<nav aria-label="Page navigation" id="alphanav">
<li class="clear active">None</li>
<a href="#">None</a>
<li>
<a href="#/">A</a>
</li>
</nav>
How do I add a <ul> right after <nav aria-label="Page navigation" id="alphanav"> and add </ul> right before </nav>?
I tried to use append but it just added <ul></ul> right after the first Nav
Advertisement
Answer
To fix this you can use the same methods of creating elements in jQuery as you already are. Simply create the ul in a jQuery object, append that to <nav> and then append your li to the ul you created. Something like the below. Note that I remove the datatable code as it wasn’t relevant to the issue.
$(document).ready(function() {
var $table = $('#reagent');
var $alphabet = $('<nav aria-label="Page navigation" id="alphanav">');
let $ul = $('<ul />').appendTo($alphabet);
let $li = $('<li class="clear active" />').data('letter', '').appendTo($ul);
$li.text('None');
for (var i = 0; i < 26; i++) {
var letter = String.fromCharCode(65 + i);
$('<li/>')
.data('letter', letter)
.html('<a href="#/">' + letter + '</a>')
.appendTo($ul);
}
$alphabet.insertBefore($table);
});<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table id="reagent"></table>