Reputation: 1950
I have dynamically created bootstrap menu links.
foreach (var link in links)
{
<li data-name="@link.Dropdown" ><a href="@Url.Action(link.Action, link.Controller, new { area = link.Area })">@Html.Raw(link.Icon) @link.LinkName</a></li>
}
Some of the links should be dropdown, so i tried to wrap them like that
$('li[data-name=School]').wrapAll("<li class='dropdown'>" +
"<a href='#' class='dropdown-toggle' data-toggle='dropdown'><i class='glyphicon glyphicon-flag'></i> School <b class='caret'></b></a>" +
"<ul class='dropdown-menu'></ul></li>");
I want to insert the matching elements between <ul class='dropdown-menu'></ul>
, but it inserts between <i></i>
. I tried this way too:
$('li[data-name=School]').wrapAll("<ul class='dropdown-menu'></ul>").before("<a href='#' class='dropdown-toggle' data-toggle='dropdown'><i class='glyphicon glyphicon-user'></i> School <b class='caret'></b></a>").wrapAll("<li class='dropdown'></li>");
Upvotes: 0
Views: 183
Reputation: 93601
Wrappings assume the content goes into the innermost element. Your wrapper has two inner elements so it would be difficult for it to chose the last one (which is what you want). Instead it targets the first one (which is the <i>
).
Step one, wrap the element in the new UL
/LI
:
$('li[data-name=School]').wrapAll("<li class='dropdown'><ul class='dropdown-menu'></ul></li>");
Step two, add back the new link:
.closest('.dropdown').prepend("<a href='#' class='dropdown-toggle' data-toggle='dropdown'><i class='glyphicon glyphicon-flag'></i> School <b class='caret'></b></a>");
Which together is simply:
$('li[data-name=School]').wrapAll("<li class='dropdown'><ul class='dropdown-menu'></ul></li>").closest('.dropdown').prepend("<a href='#' class='dropdown-toggle' data-toggle='dropdown'><i class='glyphicon glyphicon-flag'></i> School <b class='caret'></b></a>");
JSFiddle: http://jsfiddle.net/TrueBlueAussie/eLgokpd1/
Upvotes: 1