Skip to content
Advertisement

Pull the headings and display it in a div in a list format

I have a dynamic container .product_section and I need to display the headings inside to div.toc in a UL list format.

Hoping to have a script that checks every .product_section and creates a list using jquery

<div class="toc"></div>    

<div class="product_section">
  <h2>Heading 1</h2>
  <h3>Sub heading</h3>
  <h3>Sub heading</h3>
  <h3>Sub heading</h3>
</div>

<div class="product_section">
  <h2>Heading 2</h2>
  <h3>Sub heading</h3>
  <h3>Sub heading</h3>
  <h3>Sub heading</h3>
</div>

<div class="product_section">
  <h2>Heading 3</h2>
  <h3>Sub heading</h3>
  <h3>Sub heading</h3>
  <h3>Sub heading</h3>
</div>

How can I make this so that it will create a list in every .product_section

so it will be like this

<div class="toc">

<ul>
   <li><a href="#heading-1">Heading 1</a></li>
   <li><a href="#sub-heading">Sub heading</a></li>
   <li><a href="#sub-heading">Sub heading</a></li>
   <li><a href="#sub-heading">Sub heading</a></li>
</ul>

<ul>
   <li><a href="#heading-2">Heading 2</a></li>
   <li><a href="#sub-heading">Sub heading</a></li>
   <li><a href="#sub-heading">Sub heading</a></li>
   <li><a href="#sub-heading">Sub heading</a></li>
</ul>

<ul>
   <li><a href="#heading-3">Heading 3</a></li>
   <li><a href="#sub-heading">Sub heading</a></li>
   <li><a href="#sub-heading">Sub heading</a></li>
   <li><a href="#sub-heading">Sub heading</a></li>
</ul>

</div> 

Advertisement

Answer

You can try the following way:

//select all the elements with .product_section
var products = document.querySelectorAll('.product_section');
//loop through them
products.forEach(function(el){
  //create ul element
  var ul = document.createElement('ul');
  //find all h2, h3 from the currrent element
  var c = el.querySelectorAll('h2, h3');
  //loop through them
  c.forEach(function(header){
    //create li element
    var li = document.createElement('li');
    //create anchor element
    var a = document.createElement('a');  
    //set the href attribute and set the link text
    a.href = '#' + header.textContent.toLowerCase().replace(' ', '-');
    a.textContent = header.textContent;
    li.appendChild(a);
    //append the li to ul element
    ul.appendChild(li);
  });
  //append the ul to div element
  document.querySelector('.toc').appendChild(ul);
  //remove the current div element
  el.remove();
});
<div class="toc"></div>    

<div class="product_section">
  <h2>Heading 1</h2>
  <h3>Sub heading</h3>
  <h3>Sub heading</h3>
  <h3>Sub heading</h3>
</div>

<div class="product_section">
  <h2>Heading 2</h2>
  <h3>Sub heading</h3>
  <h3>Sub heading</h3>
  <h3>Sub heading</h3>
</div>

<div class="product_section">
  <h2>Heading 3</h2>
  <h3>Sub heading</h3>
  <h3>Sub heading</h3>
  <h3>Sub heading</h3>
</div>
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement