Reputation: 667
I am using the script found below to generate a table of contents.
It currently appends a table of contents to an ID. I would like to add the table of contents twice on the same page using getElementsByClassName.
I understand I need to loop through the array of elements but I just cannot get the syntax right.
Any help is much appreciated.
// External code for generating a simple dynamic Table of Contents
function generateTableOfContents(els) {
var anchoredElText,
anchoredElHref,
ul = document.createElement('UL');
document.getElementById('table-of-contents').appendChild(ul);
for (var i = 0; i < els.length; i++) {
anchoredElText = els[i].textContent;
anchoredElHref = els[i].querySelector('.anchorjs-link').getAttribute('href');
addNavItem(ul, anchoredElHref, anchoredElText);
}
}
function addNavItem(ul, href, text) {
var listItem = document.createElement('LI'),
anchorItem = document.createElement('A'),
textNode = document.createTextNode(text);
anchorItem.href = href;
ul.appendChild(listItem);
listItem.appendChild(anchorItem);
anchorItem.appendChild(textNode);
}
Upvotes: 0
Views: 53
Reputation: 3408
You are going to run into an issue there. A single element can only be appended to the document once. If you try to append it somewhere else, it will be removed from its current position first.
One possible solution to avoid that could be to use cloneNode
.
Using ES5 forEach
, a possible version of your function would be:
function generateTableOfContents(els) {
var anchoredElText, anchoredElHref,
ul = document.createElement('UL');
for (var i = 0; i < els.length; i++) {
anchoredElText = els[i].textContent;
anchoredElHref = els[i].querySelector('.anchorjs-link').getAttribute('href');
addNavItem(ul, anchoredElHref, anchoredElText);
}
// We have to use call here, because getElementsByClassName returns an array-like, not an actual array
[].forEach.call(document.getElementsByClassName('table-of-contents'), function(el) {
el.appendChild(ul.cloneNode(true));
});
// Alternative to the 3 above lines using a for
// var tocs = document.getElementsByClassName('table-of-contents');
// for (var i = 0; i < tocs.length; i++) {
// tocs[i].appendChild(ul.cloneNode(true));
// }
}
Upvotes: 1