An HTML div element contains lists of endangered species grouped by continent and the species population status.
<div> <ul data-continent="North America"> <li data-species="California condor">Critically Endangered</li> <li data-species="American bison">Near Threatened</li> </ul> <ul data-continent="Europe"> <li data-species="Cave bear">Extinct</li> </ul> </div>
Implement the function endangeredSpecies that returns how endangered a species is on a particular continent.
For example, endangeredSpecies(‘North America’, ‘American bison’) should return ‘Near Threatened’.
I have tried
const endangeredSpecies = continent => [...document.querySelectorAll(`div [data-continent="${continent}"] li`)].map(li => `${li.dataset.species}: ${li.textContent}`).join('n');
Advertisement
Answer
Since you’ll probably be calling that function repeatedly it might be more efficient to capture all of the relevant information from the HTML in an object first, and then use the function to interrogate the object rather than examining the DOM each time the function is called.
In this example buildObj
iterates over continent lists, and for each continent builds up a list of information from each list item. The final object looks like this:
{ "North America": { "California condor": "Critically Endangered", "American bison": "Near Threatened" }, "Europe": { "Cave bear": "Extinct" } }
You can then use the endangeredSpecies
function to either return the information from the object of the species on that continent if it exists, or return a default “No data” message.
Even if you didn’t want to build the object first the code in buildObj
will give you the building blocks to give you what you need.
function buildObj() { const obj = {}; const lists = document.querySelectorAll('ul'); for (const list of lists) { const { continent } = list.dataset; obj[continent] = {}; const items = list.querySelectorAll('li'); for (const item of items) { const { species } = item.dataset; const text = item.textContent; obj[continent][species] = text; } } return obj; } function endangeredSpecies(continent, species) { return obj[continent]?.[species] || 'No data available'; } const obj = buildObj(); console.log(endangeredSpecies('North America', 'American bison')); console.log(endangeredSpecies('Europe', 'Cave bear')); console.log(endangeredSpecies('Australia', 'Wookie'));
<div> <ul data-continent="North America"> <li data-species="California condor">Critically Endangered</li> <li data-species="American bison">Near Threatened</li> </ul> <ul data-continent="Europe"> <li data-species="Cave bear">Extinct</li> </ul> </div>
Additional documentation