1

This is the problem I am working on:

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>

Write a function that returns how endangered a species is on a particular continent. For example endangeredSpecies('North America', 'American bison') would return 'Near Threatened'.

Now, I did the following;

return $('ul[data-continent="+continent+"]').find('li[data-species="+species+"]').html()

Why does this not work? I thought .find would traverse the selected element (in this case traverse the child elements of ul elements with data-continent = continent) and then apply .html() to it?

Taplar
  • 24,788
  • 4
  • 22
  • 35
JoyFulCode
  • 443
  • 1
  • 6
  • 13

2 Answers2

3

Your string interpolation should look like this

return $('ul[data-continent="' + continent + '"]').find('li[data-species="' + species + '"]').html()
tom
  • 9,550
  • 6
  • 30
  • 49
  • Thank you. Though, I am confused since over here https://stackoverflow.com/questions/57789392/how-to-target-specific-attribute-with-a-certain-value-in-jquery I simply did $('p[data-topic-name='+topicName+']') so the variable in between the 2 +, was only enclosed by one set of quotation marks and it worked. But I needed to use two sets of quotations marks for the answer you provided. Why is this? – JoyFulCode Sep 04 '19 at 14:38
  • 2
    Because properly formatted attribute selectors use quotes around the value. `[attribute="value"]` or `[attribute='value']`. The choice of inner quote is dictated by what the choice of outer quote was, and is the opposite of it – Taplar Sep 04 '19 at 14:40
  • 2
    This is especially true in your case as the attribute value can have a space in it – Taplar Sep 04 '19 at 14:40
  • 1
    @Tapler exactly! – tom Sep 04 '19 at 14:41
  • 1
    As a side note, a template literal is also an option if you do not need IE support – Taplar Sep 04 '19 at 14:41
  • 1
    JoyFulCode is absolutely correct. But for fun, and in addition, you can also do this using [template literals](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals) as: ``return $(`ul[data-continent="${continent}"]`).find(`li[data-species="${species}"]`).html();``. – Oliver Sep 04 '19 at 14:41
0

Take advantage of jquery's tag find feature. The best code:

function endangeredSpecies(continent, species) { 
  return $("ul[data-continent='"+continent+"']>li[data-species='"+species+"']").text();
}
  • 1
    Please add some explanation to your answer such that others can learn from it - why is this the "best" code? – Nico Haase Jun 30 '20 at 09:32