2017-04-15 8 views
0

h2タグを挿入して、垂直ナビゲーションメニュー内のすべてのリンクの親にします。メニューリストのすべてのリンクの親を挿入します

これは1つの要素に対して行うことができますが、今はメニュー内のすべての要素に対して行います。

は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); 

私はすべてのメニュー項目のforloop内のreplaceChild()のappendChild()メソッドを使用します。

ご協力いただければ幸いです!

+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]); 
} 
関連する問題