Reputation: 39
I'm trying to write a jQuery function to take the visible h3 tags' text and append them to a side menu. I've got the text appearing in the menu correctly, but I cannot strip, then wrap them in the tags I want.
I have included the code below, can anyone see why the wrapping is not working?
function populateRightMenu() {
// empty existing menu right-menu-list
$('#right-menu-list').empty();
// get list of h3
var items = $('h3:visible');
// inject into menu
$(items).clone().unwrap('h3').wrap('<li></li>').appendTo('#right-menu-list');
}
Upvotes: 0
Views: 119
Reputation: 28611
.wrap()
doesn't return the newly wrapped parent items, it returns the existing items, so using .clone().wrap().append()
you're appending the clone, not the outer wrap.
You can fix this by selecting the new wrapper:
var items = $('h3:visible');
items.clone().wrap('<li></li>').closest("li").appendTo('#right-menu-list');
alternatively, wrap the items after appending them
items.clone().appendTo('#right-menu-list').wrap('<li></li>');
$('#right-menu-list').empty();
var items = $('#source h3');
items.clone().wrap('<li></li>').closest("li").appendTo('#right-menu-list');
$('#right-menu-list2').empty();
var items = $('#source h3');
items.clone().appendTo('#right-menu-list2').wrap('<li></li>');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="source">
<h3>1</h3>
<h3>2</h3>
<h3>3</h3>
</div>
<hr/>
<ul id="right-menu-list"></ul>
<hr/>
<ul id="right-menu-list2"></ul>
While the question is primarily about wrapp
ing with li
, there's also the question about unwrapping the h3
. Because .unwrap()
unwraps the parents, not the items themselves. So you effectively want $("h3").children().unwrap("h3")
- but .children()
doesn't select text nodes - so if your h3
s are like <h3>text</h3>
then this won't work (there's no HTML in the question, so this may be ok, or you may be ok adding eg a span
in the h3
s. The easiest method here is to extract the content directly, but this won't clone any events - so it depends on how the h3
is built
$("#right-menu-list").append(items.map(function(i,e) { return "<li>" + $(e).html() + "</li>" }).toArray())
Upvotes: 1