Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add dynamically <li> tags in jquery list?

In the moment I can add li tags to my list with script. But how can I add dynamically li tags in a function in .js? Hopefully I will see a good example. Below is my code. Thanks!

<div data-role="page" id="searchPage" data-theme="b">
<div data-role="content">
    <ul data-role="listview" data-filter="true" data-theme="b" id="searchListUl">
    </ul>
</div>
<script type="text/javascript">
  $("#searchListUl").append('<li data-filtertext="Apple"><a href="#">Apple</a></li>');
  $("#searchListUl").listview('refresh');</script></div>
like image 869
somehut Avatar asked Feb 14 '12 13:02

somehut


People also ask

How to add li tag dynamically in 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 to append data to li using jQuery?

jQuery append() MethodThe append() method inserts specified content at the end of the selected elements. Tip: To insert content at the beginning of the selected elements, use the prepend() method.

How to add item in list in jQuery?

Using append() method: The append() method in jQuery is used to add a new element at the end of the selected element. Parameter: This method accepts single parameter element which need to be inserted. Return value: It does not return anything. Example: This example uses append() method to add new element.

How to append li to ul?

To add new li to ul on click with JavaScript, we can call the appendChild method. const ul = document. getElementById("list"); const li = document. createElement("li"); li.


1 Answers

Your function would be something like:

var addItem = function(item){
    $("#searchListUl").append('<li data-filtertext="'+item+'"><a href="#">'+item+'</a></li>');
}

You can call it with: addItem("apple")

like image 137
AgnosticMantis Avatar answered Sep 23 '22 20:09

AgnosticMantis