2017-04-15 24 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]); 
}