Click here to Skip to main content
15,888,984 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I'm trying to do is get a list of items from a node js server create li tags dynamically for each one, then somehow embed the ID that is coming from the server in each created HTML element as a custom attribute or an ID. I hope this make sense.
Thanks in advanced for taking the time to help, I'm kinda new to this, so any help would be highly appreciated.
What am I doing wrong? and is there another way to accomplish this?
I included the code I tried below.


What I have tried:

JavaScript
//First getting thelist of items from the server
items.forEach(function(item) {
//adding the list to a variable to append later on to the html page
          var newItem= `<li>${item.name}</li>`;
            //I tried Jquery.data and .attr and both returns undefined
           $(newItem).data('id', item._id);
//I also tried the vanilla javascript method: .setAttribute and I get an error that it's not a function.
          newItem.setAttribute('id', item._id);

               console.log($(item).data('id'));//undefined result
Posted
Updated 2-Feb-18 4:36am
Comments
Ehsan Sajjad 2-Feb-18 8:12am    
can you log on console newItem value and see how it looks like?
random_xyz 2-Feb-18 8:27am    
Thanks you so much for your reply.
It's logging the HTML element created first, but the ID is empty, here's a screenshot: http://prntscr.com/i955u4

1 solution

Try:
JavaScript
var newItem = $("<li />").attr("id", item._id).text(item.name);
console.log("ID:", newItem.attr("id"), newItem);
 
Share this answer
 
Comments
random_xyz 2-Feb-18 12:17pm    
Thank you so much @Richard Deeming, this seems to do the trick!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900