Reputation: 325
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:
What is the best way to generate such lists according to the criteria mentioned using only JavaScript?
Upvotes: 0
Views: 1231
Reputation: 98
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!
Upvotes: 1
Reputation: 306
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?
Upvotes: 1