列出所有h1,h2

时间:2016-12-03 09:19:42

标签: javascript html

我用它来列出所有<h1>您如何将<h2>作为嵌套列表插入?

我是否应该检测到特定<h2>内的所有<h1>,即使用双循环,还是有更简单的方法?

我对使用哪种方法感到有点迷失。

var toc = document.getElementById('toc'); 
var h1 = document.getElementsByTagName("h1");
for (var i = 0; i < h1.length; i++) {
     var li = document.createElement("li");
     li.appendChild(document.createTextNode(h1[i].textContent));
     toc.appendChild(li);
}
Table of contents:

<div>
  <ul id="toc">
  </ul>
</div>  

___

<h1>TitleA</h1>
<h1>TitleB</h1>
<h2>SubTitleB1</h2>
<h2>SubTitleB2</h2>
<h1>TitleC</h1>
<h1>TitleD</h1>
<h2>SubTitleD1</h2>

2 个答案:

答案 0 :(得分:1)

您无法将选择器与getElementsByTagName()组合在一起。

可以使用querySelectorAll('h1 h2'):在节点列表中返回所有h1h2元素,您可以循环创建您的toc:

var toc = document.getElementById('toc'); 
var h1h2 = document.querySelectorAll("h1, h2");
for (var i = 0; i < h1h2.length; i++) {
  var li = document.createElement("li");
     li.appendChild(document.createTextNode(h1h2[i].textContent));
     toc.appendChild(li);
}
Table of contents:

<div>
  <ul id="toc">
  </ul>
</div>  

___

<h1>TitleA</h1>
<h1>TitleB</h1>
<h2>SubTitleB1</h2>
<h2>SubTitleB2</h2>
<h1>TitleC</h1>
<h1>TitleD</h1>
<h2>SubTitleD1</h2>

答案 1 :(得分:1)

You can use querySelectorAll获取所有for(uint32_t Y = 0; Y < mHeight; ++Y) { uint8_t* pPixel = Image.scanLine(Y); for(uint32_t X = 0; X < mWidth; ++X) { const int Blue = *pPixel++; const int Green = *pPixel++; const int Red = *pPixel++; uint8_t GrayscalePixel = (0.21f * Red) + (0.72f * Green) + (0.07 * Blue); } } h1元素的有序列表。然后,您可以处理该列表以创建带有子标题的嵌套目录:

&#13;
&#13;
h2
&#13;
// parse the ToC content
var list = document.querySelectorAll("h1,h2"); // get all h1 & h2
var tocArr = [], cur; // holds the structure of the ToC
for (var i = 0; i < list.length; i++) {
  var e = list[i];
  if (e.tagName == "H1") {
    // for an h1, create a new heading entry (with a blank child list)
    tocArr.push({text:e.textContent, children:(cur=[])});
  } else {
    // for an h2, add it to the current h1's child list
    cur.push(e.textContent);
  }
}
console.log(tocArr);

// build the DOM nodes
var toc = document.getElementById('toc');
for (var i in tocArr) {
  var li = document.createElement("li");
  li.textContent = tocArr[i].text;
  
  // NEW: add a sub-ul for any subheadings
  var ch = tocArr[i].children;
  if (ch.length > 0) {
    var ul = document.createElement("ul");
    for (var i2 in ch) {
      var li2 = document.createElement("li");
      li2.textContent = ch[i2];
      ul.appendChild(li2);
    }
    li.appendChild(ul);
  }
  
  toc.appendChild(li);
}
&#13;
&#13;
&#13;