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 >
<div >
<div >
<h4 >Text Here</h4>
<h5 >Text Here</h5>
<h6 >___ spots available</h6>
<p >Text Here</p>
<a onclick="selectDriver()" ></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?
CodePudding user response:
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 >
<div >
<div id="card_<%=i%>">
<h4 >Text Here</h4>
<h5 >Text Here</h5>
<h6 >___ spots available</h6>
<p >Text Here</p>
<a onclick="selectDriver(document.getElementById('card_<%=i%>))" ></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))" ></a>