Add items to ons-list, vanilla JS



  • I am using vanilla JS trying to figure out how to add things to an ons-list:

    <ons-list id="list">
        <ons-list-header>Numbers</ons-list-header>
        <ons-list-item>One</ons-list-item>
    </ons-page>
    

    I read about the lazy-repeat functionality but I think it is for another use. So, do I just add ons-list-items to the HTML like this or is this also the wrong approach:

    function addItem() {
        var i = document.getElementById("list");
        var c = document.createElement("ons-list-item");
        c.innerHTML = "item";
        i.appendChild(c);
        i.refresh();
    }
    

    Understanding the ons-list is very important to me. Thanks for any help!



  • @alexej Take a look at this thread: https://community.onsen.io/topic/391/onsen-2-with-jquery-and-loading-json-into-list/2

    Here is a bit of code for dynamically adding items to a list.

    var onsItem= document.createElement('ons-list-item');
           onsItem.setAttribute('modifier', "chevron");
           onsItem.setAttribute('onclick', "functionName()");
           onsItem.innerHTML = '<img src="" alt="something here" />';
    document.getElementById('listIDorSomething').appendChild(onsItem);
    

    @Fran-Diox recommends you also use:

    I’d only change onsItem.setAttribute('onclick', "functionName()"); with onsItem.onclick = function() {...};.
    


  • @munsterlander Okay so the .refresh() is not needed.

    Is anything wrong with my code though? Your example achieves a similar thing but instead you type out the img tag into the innerHTML. What’s the difference / better?

    Thanks for showing me, I understand it better now.



  • @alexej Everything looks ok. Is it failing?


Log in to reply