Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically adding <li/> to <ul/> in jquery mobile

I'm trying to add list items to unordered lists in jquery mobile, but the formatting doesn't seem to be created properly.

<ul data-role="listview" data-theme="c" data-dividertheme="b">                     <li data-role="list-divider">                         Title Divider                     </li>                     <li>                         <a href="test.html" data-transition="slide">List item 1</a>                     </li>   </ul> 

Script:

$('ul').append('<li><a>hello</a></li>'); 

For some reason the li generated dynamically doesn't display the same way as the one that's statically created. Does anyone know why and how I can make it the same?

like image 827
locoboy Avatar asked May 08 '11 05:05

locoboy


People also ask

How can add Li in UL dynamically using jQuery?

Answer: Use the jQuery append() Method You can simply use the jQuery append() method to add <li> elements in an existing <ul> element. The following example will add a <li> element at the end of an <ul> on click of the button.

How dynamically add HTML element using jQuery?

$(document). ready(function() { $('body'). on('click', '. AddEl', function() { var $elems = $('.


2 Answers

Try this:

$('ul').append($('<li/>', {    //here appending `<li>`     'data-role': "list-divider" }).append($('<a/>', {    //here appending `<a>` into `<li>`     'href': 'test.html',     'data-transition': 'slide',     'text': 'hello' })));  $('ul').listview('refresh'); 
like image 171
thecodeparadox Avatar answered Sep 22 '22 10:09

thecodeparadox


The answers provided turned out to be a little bit messy...

$('ul').append('<li><a>hello</a></li>'); is ok, but it needs to refresh the listview, so all you need is:

$('ul').append('<li><a>hello</a></li>').listview('refresh'); 
like image 35
naugtur Avatar answered Sep 23 '22 10:09

naugtur