DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Get All Country Names As A JavaScript Array

06.23.2010
| 5112 views |
  • submit to reddit
        Gets Country Names (by name) from the ForeignWorld website,
http://www.foreignword.com/countries/English.htm . May break,
depending on changes to the layout. Found it quite annoying
that no API whatsoever was provided so built a quick one myself.

Relies on appending jQuery and then traversing the DOM to
get the desired names. Works for all the languages listed
in the website.

Available with Firebug / Safari + Chrome Inspector, perhaps 
Opera Dragonfly as well.

Wait for jQuery to Load before executing the second part of 
the script. You have to clear out the last comma before
using the array, was a bit lazy to add that as well.

var j = document.createElement("script"); 
j.setAttribute("src", "http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"); 
document.getElementsByTagName("head")[0].appendChild(j);

var out = "["; jQuery.each(jQuery("tr"), function(idx, elem) { var x = jQuery(elem); var y = x.children().nextUntil(".center"); if (y.length) { var z = y.children("a[target='new']"); if (z != null) { if (z.html() != null) { out += "\"" + z.html().trim() + "\"" + ","; } } } }); out += "]"; console.log(out);

// Or, indented :

var out = "["; 
jQuery.each(jQuery("tr"), function(idx, elem) 
{ 
  var x = jQuery(elem); 
  var y = x.children().nextUntil(".center"); 

  if (y.length)
  { 
    var z = y.children("a[target='new']"); 
    if ( (z != null) && (z.html() != null) )
    { 
      out += "\"" + z.html().trim() + "\"" + ","; 
    } 
  } 
}); 

out += "]"; 
console.log(out);