Trey Trey - 2 months ago 10
jQuery Question

Jquery append and modify each of same class

I am trying to take content from a nav bar, and then modify and append it to a mobile menu. The nav bar html looks like

<div id="top_bar" class="nav">
<div class="container">
<div class="row">
<nav class="clearfix">
<a href="http://127.0.1.1:8080/my-account" class="top-bar-link"><span>My Account</span></a>
<a href="http://127.0.1.1:8080/" class="top-bar-link"><span> Rewards</span></a>
<a href="http://127.0.1.1:8080/" class="top-bar-link"><span>Customer Service</span></a>
</nav>
</div>
</div>
</div>


I need to append the anchors above to the following menu and have them work in the format below.

<ul id="stmobilemenu" class="visible-xs visible-sm show">
<li class="stmlevel0"><a href="http://127.0.1.1:8080/first" style="" class="ma_level_0">first</a></li>
<li class="stmlevel0"><a href="http://127.0.1.1:8080/second" style="" class="ma_level_0">second</a></li>
<li class="stmlevel0"><a href="http://127.0.1.1:8080/third" style="" class="ma_level_0">third</a></li>
</ul>


I tried to do this like

var add_to_menu;
$('#top_bar nav a').each(function(){
var line = '<li class="stmlevel0">';
$(this).addClass('ma_level_0');
line += $(this).html();
line += '</li>';
add_to_menu += line;

})
$('#stmobilemenu').append(add_to_menu);


The result of this was it added undefined, then it added only the content
so appeneded was in this type of format.

<li class="stmlevel0"><span>My account</span></li>


what I want it to add is in this type

<li class="stmlevel0"><a href="http://127.0.1.1:8080/my-account" style="" class="ma_level_0"><span>My account</span></a></li>


Another thing I tried was

$('#stmobilemenu').append(
$('#top_bar nav a').each(function(){
$(this).prepend('<li class="stmlevel0">');
$(this).addClass('ma_level_0');
$(this).append('</li>');
}));


I had a few problems with this though, first of all the append and prepend were not actually surrounding the html I want. It comes out like

<a href="http://127.0.1.1:8080/my-account" class="top-bar-link ma_level_0">
<li class="stmlevel0"></li>
<span>My account</span>
</a>


So I need that li to actually surround the a. Also it actually removed the content of
#top_bar nav a
from its original spot, which is not what I want it to do. I want it only to copy and add to the mobile menu. Can someone help?

Answer

Use clone() to make a copy of each <a>

var $mobMenu= $('#stmobilemenu');// store reference to menu element

$('#top_bar nav a').each(function(){
    var $link = $(this).clone().removeClass().addClass('ma_level_0'); 
    $('<li class="stmlevel0">').append($link).appendTo( $mobMenu);          
});