I'm currently designing a website that loads in a list of available items. I'm using EJS to dynamically load the items in from a database and displaying them in separate divs. However, I want the user to be able to select one of the items from the list. I've added a button to each of the divs, but I'm not sure how to make it so that when a button is pressed, it accesses the div it is nested in.
The code is below
<%for(var i = 0; i<groups.length; i++){%>
<div class="col-md-4">
<div class="card rider-card">
<div class="card-body">
<h4 class="card-title">Text Here</h4>
<h5 class="card-subtitle mb-2 text-muted">Text Here</h5>
<h6 class="card-text">___ spots available</h6>
<p class="card-text">Text Here</p>
<a onclick="selectDriver()" class="stretched-link"></a>
</div>
</div>
</div>
<%}%>
I'm using MongoDB to store the data in the database, and calling the collection as groups. I iterate through the groups and create a new card for each one. Because I'm dynamically generating the divs, I can't seem to find a way to differentiate them. The button is the anchor tag, which applies to the entire card.
Is there a way to access only the card the anchor tag is nested in?
You can use the template language to create a gradually incrementing id for each card, using the i variable in your 'for' loop:
<%for(var i = 0; i<groups.length; i++){%>
<div class="col-md-4">
<div class="card rider-card">
<div class="card-body" id="card_<%=i%>">
<h4 class="card-title">Text Here</h4>
<h5 class="card-subtitle mb-2 text-muted">Text Here</h5>
<h6 class="card-text">___ spots available</h6>
<p class="card-text">Text Here</p>
<a onclick="selectDriver(document.getElementById('card_<%=i%>))" class="stretched-link"></a>
</div>
</div>
</div>
<%}%>
That's useful if you want to refer to the card in other places also. Alternately, you could bubble up and hook into the div above via parentnodes
<a onclick="selectDriver(this.parentNode.parentNode))" class="stretched-link"></a>