List of all the countries: HTML select and JSON too

November 6th, 2016. Tagged: (x)HTML(5), JavaScript

Ever needed a list of all the countries in the world to put as options in an HTML select? Well, here you go. And JSON too. You're welcome!

But how...

How was the list derived so you can update it once in a while? Glad you asked.

https://www.iso.org/obp/ui/#search/code/ is the page linked from W3 spec so it must be the real deal.

Switch to 300 results per page so you can see all the countries.

Open console. Write magical ES.OMGWhatNext code:

Array.from($0.querySelectorAll('tr')).
  map(
    ({cells}) => 
      `<option value="${cells[2].innerText}">${cells[0].innerText}</option>`
  ).join('\n')

Wrap in select, done! Here's how it looks again.

Similarly magical code give you JSON:

JSON.stringify(
  Array.from($0.querySelectorAll('tr')).map(
    ({cells}) => {return {[cells[2].innerText]: cells[0].innerText}}
  )
)

$0?

One thing to note is the $0 which means the table of results on the ISO page. $0 is what you get when you inspect something in the console and you highlight the inspected DOM node. Instead of $0 you can currently use document.querySelectorAll('table')[2] or document.getElementsByClassName('v-table-table')[0] but who knows how soon the HTML of the page will change.

Tell your friends about this post: Facebook, Twitter, Google+

Sorry, comments disabled and hidden due to excessive spam. Working on restoring the existing comments...

Meanwhile, hit me up on twitter @stoyanstefanov