Trey Trey - 20 days ago 5x
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="" class="top-bar-link"><span>My Account</span></a>
<a href="" class="top-bar-link"><span> Rewards</span></a>
<a href="" class="top-bar-link"><span>Customer Service</span></a>

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="" style="" class="ma_level_0">first</a></li>
<li class="stmlevel0"><a href="" style="" class="ma_level_0">second</a></li>
<li class="stmlevel0"><a href="" style="" class="ma_level_0">third</a></li>

I tried to do this like

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


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="" style="" class="ma_level_0"><span>My account</span></a></li>

Another thing I tried was

$('#top_bar nav a').each(function(){
$(this).prepend('<li class="stmlevel0">');

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="" class="top-bar-link ma_level_0">
<li class="stmlevel0"></li>
<span>My account</span>

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?


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);