Hey there!
It is possible, but it will be a shift in mindset and development paradigm. What you are used to, right now, is that only one unique ID corresponds to one element and that is what you shift around.
However, there is a better way, that works for a variable amount of elements, we can automate that, without using the id
attribute.
What you want is to think about state and which data has to be displayed where.
So given your example, you have an array of products:
let products = [
{
name: 'Product 1',
selected: false,
price: 10.5,
},
{
name: 'Product 2',
selected: false,
price: 4.5,
},
{
name: 'Product 3',
selected: false,
price: 5,
},
]
Feel free to extend your product with whatever properties you need.
So what we need to do, is to read out the checked
state of an input associated with the product and keep it in sync with the correct products selected
property.
Front-end frameworks such as VueJS make this very easy, compared to vanilla JS, because keeping state in sync with the DOM is a difficult task. If you want to make it render efficiently, you should also avoid using setting innerHTML
directly, but for our example, it is okay. The right way is to use document.createElement
but that is too cumbersome to do manually.
The HTML
Straightforward, if we use JS to populate the cart and products, all we need is a container:
<h2>Products</h2>
<div class="products"></div>
<h2>Cart</h2>
<div class="cart"></div>
The templates
So you want to re-use a snippet of HTML for your product, that you populate with the state of your product object.
Product
<div class="product product-${index}">
<div class="product-info">${product.name} - ${product.price} $</div>
<input type="checkbox" ${product.selected ? 'checked' : ''}>
</div>
All your products variables + the array index are available here. This gets populated when rendering.
The hard part is about the eventlisteners. You need to listen for changes to the checkbox element for each product and then re-render the products and the card accordingly.
I created a simple demo on codepen:
If you want to read about the problem full in-depth, I wrote about this problem with your example: https://happy-css.com/articles/component-oriented-ui-webdevelopment-with-vanilla-js/