将标头解析为无序列表IN PLAIN JS

时间:2014-05-01 14:32:17

标签: javascript dom

我的剧本的一部分

function lab()
{
var h1 = getElementsByTagName("H1");
var li = document.createElement("LI");
var ul = document.createElement("UL");
li.innerHTML = h1.innerHTML;
h1[0].parentNode.replaceChild(ul,h1[0]);
h1[0].parentNode.appendChild(li);
}

什么都不做。

整个任务是仅使用带有DOM的普通js将标题组合更改为无序列表。这里已经存在一个问题,但遗憾的是,jQuery提供的解决方案不是简单的JS。

你可以给我一个暗示吗?

1 个答案:

答案 0 :(得分:1)

我不确定你到底需要什么,也许是这样的:

function lab() {
    var h1 = document.getElementsByTagName('h1'), // Create a collection of H1 elements
        ul = document.createElement('ul'),        // Create a new UL element
        parent = h1[0].parentNode,                // Store the parent node of the first H1
        n, len, li;                               // Declare some variables to use later
    for (n = 0, len = h1.length; n < len; n++) {  // Iterate through H1 elements
        li = document.createElement('li');        // Create a new LI element
        li.appendChild(h1[0]);                    // Move a H1 to LI (Live collection, 0 instead of n as index)
        // Or switch the line above to the next two lines, if you want to remove the H1 and list the content only
        // li.innerHTML = h1[0].innerHTML;
        // h1[0].parentElement.removeChild(h1[0]);// If you want to preserve H1s, remove this line
        ul.appendChild(li);                       // Append the newly-created LI to the UL
    }
    parent.appendChild(ul);                       // Append the UL to the parent
}

这会将所有H1元素收集到无序列表中,该列表将附加到第一个H1的父元素。

A live demo at jsFiddle