rob.m rob.m - 1 month ago 7
jQuery Question

How to get the list of the first column value from wikipedia table?

I am trying to get the list of years in the first column of the first wikipedia table here (Start) and place it inside a select

I am reading the json this way but i cannot grab what I need in order to place it in a select:

$(document).ready(function(){

$.ajax({
type: "GET",
url: "https://en.wikipedia.org/w/api.php?action=parse&format=json&prop=text&section=1&page=List_of_wars_1000%E2%80%931499&callback=?",
contentType: "application/json; charset=utf-8",
async: false,
dataType: "json",
success: function (data, textStatus, jqXHR) {

var markup = data.parse.text["td"];
var i = $('<div></div>').html(markup);

// remove links as they will not work
i.find('a').each(function() { $(this).replaceWith($(this).html()); });

// remove any references
i.find('sup').remove();

// remove cite error
i.find('.mw-ext-cite-error').remove();

$('#article').html($(i).find('p'));
},
error: function (errorMessage) {
}
});

});

Answer

Here is one solution for your:

$(document).ready(function(){
    $.ajax({
        type: "GET",
        url: "https://en.wikipedia.org/w/api.php?action=parse&format=json&prop=text&section=1&page=List_of_wars_1000%E2%80%931499&callback=?",
        contentType: "application/json; charset=utf-8",
        async: false,
        dataType: "json",
        success: function (data, textStatus, jqXHR) {
          var html = data.parse.text['*'];

          if(!html) {
            return;
          }

          var $hiddenContent = $('<div/>').html(data.parse.text['*']).hide();
          var $firstColumnCells = $hiddenContent.find('table.wikitable').find('td:first-child');
          $hiddenContent.remove(); // remove our helper div

          var values = [];
          $firstColumnCells.each(function(idx, cell) {
            
            var val = $(cell).text().match(/\d+/)[0];
            
            values.push($(cell).text());
            // you can also do something here with the value
            $('#article').append('<div>'+ val + '</div>');
          });

          // show as array in your console if you like or doSomething with the array
          //console.log(values);       
        },
        error: function (errorMessage) {
        }
    });    

});
#article div {
  padding: 5px;
  margin: 5px 0;
  background: grey;
  width: auto;
  color: white;
  width: 100px;
  text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="article">
  <h2>Years</h2>
</div>

Comments