ちょっとしたことですが、頭を悩ませています。
メニュー内の要素を検出するためにJavaScriptを使用しています:
var nav = document.getElementById('nav');
var list = nav.children.length;
メニューはドロップダウン用にネストされていますが<ul>
、これらをターゲットにするにはどうすればよいですか?
ちょっとしたことですが、頭を悩ませています。
メニュー内の要素を検出するためにJavaScriptを使用しています:
var nav = document.getElementById('nav');
var list = nav.children.length;
メニューはドロップダウン用にネストされていますが<ul>
、これらをターゲットにするにはどうすればよいですか?
nav.getElementsByTagName('ul')
内のすべての<ul>
要素を提供しますnav
。
DOMでのより複雑な検索の場合は、CSSスタイルを適用する方法(、など)で要素querySelector/querySelectorAll
を選択するために使用できます。'#id ul'
'.someClass'
あなたのコードを見て、実際にフィドルを読んで見た後、必要なものを誤解していたので、他の答えを削除しました...
つまり、見つかったときにすべての子 ul をトラバースする再帰関数を作成する必要があります。私は自分の開発環境を実行していないので、これを疑似コード化します(そして、ドリフトが得られると確信しています)
RecursiveFunction(document.getElementById('nav'), "-");
//他の場所
function RecursiveFunction(domElement, prependedChar)
{
//because this is .js you will probably need some closures...
var currPrependedChar = prependedChar;
var dom = domElement;
//iterate all nodes, check if they are a li/a and populate dropdown...
for(count;count < dom.list.Length;++count){
//if the element you have found is a ul recurse
if(dom.list[count] == "ul"){
RecursiveFunction(dom.list[count], currPrependedChar + currPrependedChar ); //this calls this function
}else{
//combobox option.Value = currPrependedChar + elementInnerText
}
}
}
これはフィドル形式の完成した再帰関数です
コード
function RecursiveFunction(currDom, currPrependedChar) {
//because this is .js you will probably need some closures...
var prependedChar = currPrependedChar;
var dom = currDom;
var children = dom.children;
var childrenCount = children.length;
//iterate all nodes, check if they are a li/a and populate dropdown...
for (var i = 0; i < childrenCount; ++i) {
var curElem = children[i];
//if the element you have found is a ul recurse
switch (curElem.nodeName) {
case "A":
var option = document.createElement('option');
option.innerHTML = prependedChar + curElem.text;
option.value = curElem.href;
select.appendChild(option);
break;
default:
if(curElem.nodeName == "UL") prependedChar += prependedChar
RecursiveFunction(curElem, prependedChar);
break;
}
}
}