dongmeiran609914 2016-05-30 20:08
浏览 68
已采纳

如何从当前页面制作标题列表(h2元素)并在旁边部分将它们打印成ul

I am trying to automatically generate a list of headings (name of the topics) from the current page. It should be displayed in the aside element of the page.

This is what I have so far:

<main>
<h2>Topic 1</h2>
<h2>Topic 2</h2>
<h2>Topic 3</h2>
<h2>Topic 3</h2>
</main>
<aside>
  <!--automaticly generated list of heading 
  like:
  <ul>
  <li>Topic 1</li>
  <li>Topic 2</li>
  <li>Topic 3</li>
  <li>Topic 4</li>
  </ul>
  -->
  
</aside>

What do I need to do to finish this?

</div>
  • 写回答

2条回答 默认 最新

  • dtrj74376 2016-05-30 20:42
    关注

    Well, there are different methods. Here you have one!

    <main>
      <h2>Topic 1</h2>
      <h2>Topic 2</h2>
      <h2>Topic 3</h2>
      <h2>Topic 3</h2>
    </main>
    <aside>
      <!--automaticly generated list of heading
      like:
      <ul>
      <li>Topic 1</li>
      <li>Topic 2</li>
      <li>Topic 3</li>
      <li>Topic 4</li>
      </ul>
      -->
    
    </aside>
    
    <script type="text/javascript">
    
      var //Array with all the elements with tag main. It is a collection
          mainEl = document.getElementsByTagName("main"),
          //Because we only have one main tag, from the previous
          //collection we chose the first elemnt
          //From that element we create a collection with all the h2 inside
          headingsEls = mainEl[0].getElementsByTagName("h2"),
          //collection of elements with "aside" tag
          asideEl = document.getElementsByTagName("aside"),
          //We create the ul that wil hold the list
          ulEl = document.createElement("ul")
    
      //Go throw the h2 collection and for each element we create a new li element,
      //we pass to it the text content and we put it on the ul
      for(var i = 0; i < headingsEls.length; i++){
        var liEl = document.createElement("li")
        liEl.textContent = headingsEls[i].textContent
        ulEl.appendChild(liEl)
      }
    
      //the new ul with the list is appended!
      asideEl[0].appendChild(ulEl)
    </script>
    

    I have tried to be very descriptive but ask if you have more doubts!

    Edited: I forgot that Array.from was implemented in ES2015. Changed the forEach to a for loop instead.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突