Can someone help me create a Dynamic List with Href.. I only know how to add a list but I don't know how to add links for every list
<h1>Toppings</h1>
<ul>
</ul>
<script>
var toppings = ['tomatoes', 'olives', 'cheese', 'peperonies']
</script>
Now i want to have a dynamic list with links not just list. Can someone help me.
You need to create an anchor tag inside a list item for each topping and append it to your unordered list
<h1>
Toppings
</h1>
<ul id="toppings-list">
</ul>
<script>
let toppings = ['tomatoes', 'olives', 'cheese', 'peperonies'];
const toppingsList = document.querySelector('#toppings-list');
toppings.forEach(topping => {
const listItem = document.createElement('li');
const link = document.createElement('a');
link.setAttribute('href', topping);
link.innerText = topping;
listItem.appendChild(link);
toppingsList.appendChild(listItem);
});
</script>
The traditional way is with the .createElement and .appendChild methods.
Edit:
Inserting links depends on where you want the links to go (of course) but the snippet now includes a crude demonstration of dynamically creating anchor elements related to each list item.
const toppings = ['tomatoes', 'olives', 'cheese'];
const myUl = document.getElementById("my-ul");
for(let topping of toppings){
const newLi = document.createElement("li");
const newAnchor = document.createElement("a");
newAnchor.href = "#" + topping;
newAnchor.textContent = topping;
newLi.appendChild(newAnchor);
myUl.appendChild(newLi);
}
<h1>Toppings</h1>
<ul id="my-ul"></ul>
<div>-</div><div>-</div><div>-</div>
<div id="tomatoes">tomatoes target</div>
<div>-</div><div>-</div><div>-</div>
<div id="olives">olives target</div>
<div>-</div><div>-</div><div>-</div>
<div id="cheese">cheese target</div>
<div>-</div><div>-</div><div>-</div>
<div>-</div><div>-</div><div>-</div>
<div>-</div><div>-</div><div>-</div>
<div>-</div><div>-</div><div>-</div>
<div>-</div><div>-</div><div>-</div>