I’m working on a dropdown menu and need to mutate the existing html markup with JQuery to make it fit the design.
Here is a simplified example:
Wrap all “ul’s” that contain more than one “li” in a div (in the same div, NOT one div for each UL).
<ul>
<li>foo</li>
</ul>
<ul>
<li>foo</li>
<li>foo</li>
</ul>
<ul>
<li>foo</li>
<li>foo</li>
</ul>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script>
my_selection = [];
i = 0;
// find all ul's that have more than one li
$("ul").each(function(){
if($(this).find("li").length > 1){
// add this to my_selection
my_selection[i] = $(this);
i++;
} // if
}); // each
// wrap my_selection in div tags
$(my_selection).wrapAll(document.createElement("div"));
</script>
The above code gives this firebug error:
“Node cannot be inserted at the specified point in the hierarchy” code: “3”
How can I make it work?
This would be a much cleaner approach:
First, you don’t need to create the node, just provide the wrapping string to jQuery.
Second, use the
:hasselector in this instance to cut down on theeachfunctionality in your example.Finally, (this will depend on your intended functionality) you may want to use
wrapinstead ofwrapAll.EDIT:
Another option would be to approach it from the other way around. Get the
<li>tags then grab the<ul>parent: