How to add a list item to an existing unordered list, dynamically?

Raj
Raj
Member
496 Points
21 Posts

I have following html code for unordered list:

<div id="menu-header">
    <ul class="tabs">
        <li><a href="/customer/view"><span class="tab">Profile</span></a></li>
        <li><a href="/customer/edit"><span class="tab">Edit</span></a></li>
    </ul>
</div>

And I want to add following li html dynamically with jQuery:

<li><a href="/customer/messages"><span class="tab">Messages</span></a></li>

I'm trying as following but not working as expected:

$("#menu-header ul li:last").append("<li><a href="/customer/messages"><span class="tab">Messages</span></a></li>");

what will be correct way for this?

 

Views: 830
Total Answered: 2
Total Marked As Answer: 1
Posted On: 11-Feb-2022 02:58

Share:   fb twitter linkedin
Answers
beginer
beginer
Member
1328 Points
43 Posts
         

Try following code:

$("#menu-header ul").append('<li><a href="/customer/messages"><span class="tab">Messages</span></a></li>');
Posted On: 14-Feb-2022 05:50
Rashmi
Rashmi
Member
820 Points
17 Posts
         

We can also, do with object and more easy to implement:

$('#menu-header ul').append(
    $('<li>').append(
        $('<a>').attr('href','/customer/messages').append(
            $('<span>').attr('class', 'tab').append("Messages")
)));

OR

var span = $('<span>').attr('class', 'tab').append("Messages");
var anchor = $('<a>').attr('href','/customer/messages').append(span);
var li = $('<li>').append(anchor);
$('#menu-header ul').append(li)
Posted On: 17-Feb-2022 04:52
Thanks Rashmi
 - Raj  17-Feb-2022 21:37
 Log In to Chat