简体   繁体   中英

What is the best way to generate a list of HTML elements dynamically using JavaScript?

A lot of important web sites like Amazon, Facebook, Twitter... essentially consist of a list HTML elements being divs or others that are generated dynamically from a search query or from a menu selection. For example:

  • Amazon : a list of products
  • Facebook : a list of posts
  • Twitter : a list of twitters

What is the best way to generate such lists according to the criteria mentioned using only JavaScript?

Facebook for example use React to generate dynamic content on the client side. It's a good library ( framework) for that kind of things... but im gonna answer your question. I guess that's the correct way to deal with dynamic content on javascript "by hand", just javascript.

From the W3Schools.

var fruits = ["apple", "orange", "cherry"]; fruits.forEach(myFunction);

//HTML

function myFunction(item, index) { document.getElementById("demo").innerHTML += index + ":" + item + "
"; }

that's the approach used for dynamic content. Here's the proper answer to your question How to create list in HTML dynamically?

To do this with vanilla JavaScript, you want to start with an array of stuff to be displayed, then iterate over the list and call document.createElement for each item. There are many ways to implement this. One example would look something like this:

const testStuff = [ 'product 1', 'product 2', 'product 3' ]

for (let i = 0; i < testStuff.length; i++) {
  let element = document.createElement('div');
  element.innerHTML = testStuff[i];
  document.getElementsByTagName('body')[0].appendChild(element);
}

This would result in 3 divs in the body of the HTML document with each of the values from the array. It is worth pointing out that all of the companies that you listed above are definitely using ES6 syntax and JavaScript frameworks to make this whole thing easier.

Hope that helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM