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

Raj
Raj
648 Points
26 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: 1118
Total Answered: 2
Total Marked As Answer: 1
Posted On: 11-Feb-2022 02:58

Share:   fb twitter linkedin
Answers
beginer
beginer
1544 Points
52 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
1068 Points
19 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