2017-04-15 26 views
0

我試圖插入h2標籤,並使它們成爲垂直導航菜單中所有鏈接的父母。爲菜單列表中的所有鏈接插入父母

我可以爲單個元素做到這一點,但現在我想爲菜單中的所有元素做到這一點。

的JavaScript:

var menu_item = document.querySelector("div.righ-nav-style1 ul li a");  

// `menu_item` is the element you want to wrap 
var parent = menu_item.parentNode; 
var wrapper = document.createElement('h2'); 
wrapper.className = 'category_links';  

// set the wrapper as child (instead of the 'menu_item') 
parent.replaceChild(wrapper, menu_item); 
// set 'menu_item' as child of wrapper 
wrapper.appendChild(menu_item); 

我想用的replaceChild()使用appendChild()方法for循環之內的所有菜單項。

任何幫助將不勝感激!

+1

添加您的解決方案在下面的部分答案 –

回答

0

編輯:我其實只是找到了解決我的問題。

編輯的JavaScript:

// Replaced 'querySelector()' with 'querySelectorAll()' to get all elements 
var menu_item = document.querySelectorAll("div.righ-nav-style1 ul li a");    

// Created 'for' loop to use 'replaceChild()' and 'appendChild()' methods for all elements 
for (var i = 0; i < menu_item.length; i++){ 
    var parent = menu_item[i].parentNode; 
    var wrapper = document.createElement('h2'); 
    wrapper.className = 'category_links';  

    // set the wrapper as child (instead of the 'menu_item') 
    parent.replaceChild(wrapper, menu_item[i]); 
    // set 'menu_item' as child of wrapper 
    wrapper.appendChild(menu_item[i]); 
}