簡體   English   中英

在菜單列表中為所有鏈接插入父母

[英]Insert Parents for all links in menu list

我正在嘗試插入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); 

我想在forloop中為所有菜單項使用replaceChild()appendChild()方法。

任何幫助將不勝感激!

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

編輯的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]);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM