-1

I have an app in which I dynamically add unordered lists to a div with id="rows" Each time I add an unordered list, I want to add list items to it. My code does not add the list items to the list. Instead, it adds the list items as children of the div rather than children of the unordered list.

Here is the HTML

<body>
        <div id="colNames">
            <button class="ui-button ui-widget ui-corner-all" id="add-column">Add Column</button>
            <button class="ui-button ui-widget ui-corner-all" id="clear-column-list">Clear Columns</button>
            <ul id="column-list">
            </ul>           
        </div>
        <div id="rows">
            <button class="ui-button ui-widget ui-corner-all" id="add-row">Add Row</button>
        </div>
        <div id="buttons">
            <button class="ui-button ui-widget ui-corner-all" id="create-table">Generate Table Markdown</button>
        </div>
    </body>

Here is the code that is not working

let colNameArray = ["a", "b"];
    let newRow = $("#rows").append("<ul></ul>");
     for (let i in colNameArray) { 
        let name = colNameArray[i];
        $(newRow).append("<li><p>  " + name + "</p><input type='text'></li>");
     }

My project has separate files for html, script, and css. Let me know if you need to see the entire project.

Steve Murphy
  • 431
  • 2
  • 7
  • 17
  • Define "not working" in technical terms. Any errors or observable, unwanted behaviour? – tadman Aug 13 '23 at 20:37
  • You may want to use `colNameArray.forEach(name => ...)` to avoid all the indexing clutter. What I'd do is `map()` the entries into their respective elements (using [template literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals)) and then wrap that in the `
      ...
    ` for final insertion.
    – tadman Aug 13 '23 at 20:38
  • `.append()` doesn't return the appended element. – gre_gor Aug 13 '23 at 20:48
  • 1
    Does this answer your question? [jQuery append() - return appended elements](https://stackoverflow.com/questions/2159368/jquery-append-return-appended-elements) – gre_gor Aug 13 '23 at 20:50
  • Thanks @tadman. "not working": My code does not add the list items to the list. Instead, it adds the list items as children of the div rather than children of the unordered list. In any case, I'm trying your map() suggestion. – Steve Murphy Aug 14 '23 at 15:25
  • @gre_gor. I'm still reading the link for comprehension. Thank you – Steve Murphy Aug 14 '23 at 15:26
  • 2
    `$("#rows").append("
      ");` returns `#rows`. `$("
        ").appendTo("#rows")` returns the newly added `ul`
        – freedomn-m Aug 14 '23 at 15:26

      0 Answers0