Skip to content

Instantly share code, notes, and snippets.

@nexpr
Created December 4, 2015 08:53
Show Gist options
  • Save nexpr/6f7ddb3e37cac43f24f7 to your computer and use it in GitHub Desktop.
Save nexpr/6f7ddb3e37cac43f24f7 to your computer and use it in GitHub Desktop.
h系タグからインデックスを作る
function makeIndex(get_elem_selector, set_elem_selector){
var glem = document.querySelector(get_elem_selector)
var slem = document.querySelector(set_elem_selector)
if(!glem || !slem) throw "element not found"
var hs = []
!function recur(elem){
var match = elem.tagName.match(/^H([1-9])$/)
if(match){
hs.push([+match[1], elem.textContent])
}else{
[].forEach.call(elem.children, recur)
}
}(glem)
var etree = function(){
var root = document.createElement("ul")
var now_level = 1
var ptr = root
hs.forEach(function(e){
var level = e[0]
var text = e[1]
if(now_level < level){
level_in(level - now_level)
}else if(now_level > level){
level_out(now_level - level)
}
add_elem(text)
now_level = level
})
return root
function level_in(n){
while(n--){
// make "li" if empty "ul"
if(!ptr.lastElementChild){
ptr.appendChild(document.createElement("li"))
}
var ul = document.createElement("ul")
ptr.lastElementChild.appendChild(ul)
ptr = ul
}
}
function level_out(n){
while(n--){
ptr = ptr.parentElement.parentElement
}
}
function add_elem(text){
var li = document.createElement("li")
li.textContent = text
ptr.appendChild(li)
}
}()
slem.appendChild(etree)
return etree
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment