I have a div with children that I need to crawl looking for specific links. The HTML looks like so:
<div id="ctl00_LeftNav">
<h3>
<a href="../App_Templates/#" rel="0">Menu 1</a></h3>
<div>
<p>
<span>
<div style="padding-left: 0px; font-weight: bold;">
<a href="javascript:OnLeftMenuSelection(1);">Opt 1</a></div>
<div style="padding-left: 10px;">
<a href="javascript:OnLeftMenuSelection(56);">Opt 1a</a></div>
<div style="padding-left: 0px; font-weight: bold;">
<a href="javascript:OnLeftMenuSelection(2);">Opt 2</a></div>
</span>
</p>
</div>
<h3>
<a href="../App_Templates/#" rel="1">Menu 2</a></h3>
<div>
<p>
<span>
<div style="padding-left: 0px; font-weight: bold;">
<a href="javascript:OnLeftMenuSelection(33);">Opt 1</a></div>
<div style="padding-left: 0px; font-weight: bold;">
<a href="javascript:OnLeftMenuSelection(34);">Opt 2</a></div>
<div style="padding-left: 10px;">
<a href="javascript:OnLeftMenuSelection(42);">Opt 2a</a></div>
</span>
</p>
</div>
<h3>
<a href="../App_Templates/#" rel="2">Menu 3</a></h3>
<div>
<p>
<span>
<div style="padding-left: 0px; font-weight: bold;">
<a href="javascript:OnLeftMenuSelection(58);">Opt 1</a></div>
<div style="padding-left: 0px; font-weight: bold;">
<a href="javascript:OnLeftMenuSelection(59);">Opt 2</a></div>
</span>
</p>
</div>
</div>
The Javascript that I have works fine in IE / Firefox, but fails in Chrome:
function OnPageLoadCategorySelect(Category) {
var Root = $j('#ctl00_LeftNav').children();
var Tab = 0;
for (var i = 1; i < Root.length; i += 2) {
var Menu = Root[i].firstChild.firstChild.childNodes;
var MenuLength = Menu.length;
for (var j = 0; j < Menu.length; j++) {
var Link = Menu[j].innerHTML;
var Start = Link.indexOf('(');
var End = Link.indexOf(')');
var Res = Link.slice(Start + 1, End);
if (Res == Category) {
SelectedTabIndex = Tab;
OnLeftMenuSelection(Category);
$j('#ShopTabs').show();
$j('#ctl00_LeftNav').accordion('activate', Tab);
return;
}
}
Tab++;
}
}
In Chrome the 2nd for loop never executes because Menu.length is zero. What would be the best way to get these internal divs?
Solution
function OnPageLoadCategorySelect(Category) {
$j("#ctl00_LeftNav > div").each(function(Tab, el) {
$j('a', this).each(function() {
var id = $j(this).attr('href').replace('javascript:OnLeftMenuSelection(', '').replace(');', '');
if (id == Category) {
SelectedTabIndex = Tab;
OnLeftMenuSelection(Category);
$j('#ShopTabs').show();
$j('#ctl00_LeftNav').accordion('activate', Tab);
return false; // exit the loop
}
})
});
}