Example
Suppose I have an array of school objects in javascript...
schools =
[
{name: "School A", phone: "Phone A", location: "Location A"},
{name: "School B", phone: "Phone B", location: "Location B"},
{name: "School C", phone: "Phone C", location: "Location C"},
...
]
... and I want to display the schools names in paragraph tags ...
<p data-name="School A">School A</p>
<p data-name="School B">School B</p>
<p data-name="School C">School C</p>
... when I click on a given school paragraph, I want to display the additional info in a separate pane. For example, when I click on School A...
<div id="separate-pane">
<p>Phone A</p>
<p>Address A</p>
</div>
To do this, I need to retrieve the associated object, create the additional info paragraph tags, and append them to the separate pane. How do I go about referencing the correct javascript object when clicking on a given school name paragraph in an efficient way?
Thoughts/Ideas
Use innerHTML
- On click paragraph, extract the school name from innerHTML
- Iterate through javascript array and when obj.name == innerHTML, we have found a match
Use data-name attribute
- Same as above, but obj.name == data-name
Both of these ways should work, but is there a better way to do this without having to iterate through the javascript array to find the correct object? Also, what is this process called that I am trying to accomplish?