Note that there are some explanatory texts on larger screens.

plurals
  1. POWrap items only if they are not already within a certain element
    text
    copied!<p>jquery dom jquery-selectors simple issue, but I cannot nail it. I am crating a mega menu by manipulating a simple <strong></strong> list element.</p> <p>My menu structure looks something like this:</p> <pre><code>&lt;ul&gt; &lt;li&gt; &lt;a href="#"&gt;Something&lt;/a&gt; &lt;ul&gt; &lt;li&gt; &lt;a href="#"&gt;Some Sub Menu Item&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; </code></pre> <p>On hover I have a simple rule: Find all <strong>second level</strong> <code>&lt;li&gt;</code> elements and wrap them in a with class <strong>.subMenuContainer</strong></p> <p>Therefore, on hover, the above is transformed to this:</p> <pre><code>&lt;ul&gt; &lt;li&gt; &lt;a href="#"&gt;Something&lt;/a&gt; &lt;ul&gt; &lt;div class="subMenuContainer"&gt; &lt;li&gt; &lt;a href="#"&gt;Some Sub Menu Item&lt;/a&gt; &lt;/li&gt; &lt;/div&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; </code></pre> <p>Simply put, sub menu items are wrapped in a div so they can be positioned specifically.</p> <p>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.</p> <p>My jQuery rule for wrapping these <li> elements is as follows:</p> <pre><code>$('ul.someClass li').bind('mouseover', function(){ $(this).find('ul').not(':contains(div.subMenuContainer)').find('li').wrapAll('&lt;div class="subMenuContainer" /&gt;'); }); </code></pre> <p>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 ?</p> <p>Am I missing something?</p> <p>Regards, Simon</p> <p>[EDIT] - See chosen answer below, the solution was simply to use <strong>></strong> when searching for elements, eg: <code>$('ul &gt; li')</code> which causes only <code>&lt;li&gt;</code> items that are direct children of the <code>&lt;ul&gt;</code> (and not in the div) to be found. Thank you.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload