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>
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.
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.
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.
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.
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With