jquery dom jquery-selectors simple issue, but I cannot nail it. I am crating a mega menu by manipulating a simple list element.
My menu structure looks something like this:
<ul>
<li>
<a href="#">Something</a>
<ul>
<li>
<a href="#">Some Sub Menu Item</a>
</li>
</ul>
</li>
</ul>
On hover I have a simple rule: Find all second level <li> elements and wrap them in a with class .subMenuContainer
Therefore, on hover, the above is transformed to this:
<ul>
<li>
<a href="#">Something</a>
<ul>
<div class="subMenuContainer">
<li>
<a href="#">Some Sub Menu Item</a>
</li>
</div>
</ul>
</li>
</ul>
Simply put, sub menu items are wrapped in a div so they can be positioned specifically.
This works fine on the first hover, but on the second hover the subMenuContainer is wrapped yet again, so for ‘X’ amount of hovers I end up with ‘X’ amount of subMenuContainer elements.
My jQuery rule for wrapping these
$('ul.someClass li').bind('mouseover', function(){
$(this).find('ul').not(':contains(div.subMenuContainer)').find('li').wrapAll('<div class="subMenuContainer" />');
});
Surely by using the above code the items should only be wrapped in the div if there is not already a div with class .subMenuContainer inside the ?
Am I missing something?
Regards,
Simon
[EDIT] – See chosen answer below, the solution was simply to use > when searching for elements, eg: $('ul > li') which causes only <li> items that are direct children of the <ul> (and not in the div) to be found. Thank you.
This happens because :contains is for usage with text, not elements.
Try this:
or
Only li’s that are immediate childs of ul are wrapped now.