heading element에 multi-level 넘버링 하기
아래와 같은 html 이 있을 경우 ‘first h2 in first h1′ 앞에는 1.1 이 아닌 1이라는 번호가 출력되게 됩니다.
<ol> <li> <h1>first h1</h1> <ol> <li><h2>first h2 in first h1</h2></li> <li><h2>second h2 in first h1</h2></li> </ol> </li> <li> <h1>second h1</h1> <ol> <li><h2>first h2 in second h1</h2></li> <li><h2>second h2 in second h1</h2></li> </ol> </li> </ol> |
하지만 요청에 의해 ‘1. first h2 in first h1′ 이 아닌 ‘1.1. first h2 in first h1′ 식의 출력이 필요하게 되었는데, css의 generated content와 counter는 일부 브라우져에서 밖에 지원하지 않는다는 제약이 있습니다.[1]
당연히 이를 위한 스크립트가 있을 줄 알았는데, 제 검색 능력 부족인지 검색이 잘 안되네요. 아쉬운 사람이 우물을 판다고 간단한 스크립트를 작성해보았습니다.
function multilevellist(){ items = document.getElementsByTagName('li'); var h2 = 0; var h3, h4; for( i = 0 ; i < items.length ; i++ ){ if( items[i].parentNode.tagName == 'ul' || items[i].parentNode.tagName == 'UL' ) continue; childs = items[i].childNodes; for( j = 0 ; j < childs.length ; j++ ){ if( childs[j].tagName == 'H2' || childs[j].tagName == 'h2' ){ h2++; childs[j].innerText = h2 + '. ' + childs[j].innerText; h3 = 0; } if( childs[j].tagName == 'H3' || childs[j].tagName == 'h3' ){ if( h2 < 2 ) continue; h3++; childs[j].innerText = h2 + '.' + h3 + '. ' + childs[j].innerText; h4 = 0; } if( childs[j].tagName == 'H4' || childs[j].tagName == 'h4' ){ h4++; childs[j].innerText = h2 + '.' + h3 + '.' + h4 + '. ' + childs[j].innerText; h5 = 0; } } } } |
Ordered List 안에 있는 h1, h2, h3, h4 에 대해 1, 1.1, 1.1.1, 1.1.1.1 식으로 번호를 메겨주는 역할을 하는 스크립트이며 body의 onload 이벤트에 multilevellist() 함수를 연결해주기만 하면 알아서 작동합니다.
오늘의 삽질 끝!!
덧: 보니까 parentElement가 IE에선 동작하질 않네요. parentNode로 대체 했습니다.
- Internet explorer 때문에 간단한 일을 복잡하게 처리해야한다는 현실이 너무 슬픕니다. [↩]
Related Posts
This entry was posted by 정태영 on Friday, May 29th, 2009 at 5:29 PM and is taged under automatic, css, element, heading, html, javascript, list, multi-level, numbering. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.