Parse an HTML string to get contents of elements with Javascript

Chris Armstrong picture Chris Armstrong · Dec 4, 2010 · Viewed 12k times · Source

I have the following string that contains several elements:

'<span class="fn" id="fn1">Matthew</span>
<span class="spouse" id="spouse1">Evelyn Ross</span>
<span class="bday" id="bday1">1456</span>
<span class="wday" id="wday1"></span>
<span class="dday" id="dday1">2000</span>'

What would be the best way to parse this out to 5 variables?

EDIT

For clarity, here's the full code, I'm creating a custom input type for jEditable that allows me to inline edit a vcard.

   $.editable.addInputType('person', {
    element : function(settings, original) {     
   var fn  = $('<input id="fn_"/>');
  var bday  = $('<input id="bday_" />');
  var wday  = $('<input id="wday_" />');
  var dday  = $('<input id="dday_" />');
  var spouse  = $('<input id="spouse_" />');

  $(this).append(fn);
  $(this).append(bday);
  $(this).append(wday);
  $(this).append(dday);
  $(this).append(spouse);

        /* Hidden input to store value which is submitted to server. */
        var hidden = $('<input type="hidden">');
        $(this).append(hidden);
        return(hidden);
    },

 content : function(string, settings, original) {
   var $data = $(string);

   var data = {};
   $data.each(function () {
       var $t = $(this);
       data[$t.attr('id')] = {
                              class: $t.attr('class'),
                              value: $t.text()};
   });

   alert(data.length());

   $("#fn_", this).val('Name');
   $("#bday_", this).val('Born');
   $("#wday_", this).val('Married');
   $("#dday_", this).val('Died');
   $("#spouse_", this).val('Spouse');
     },

  submit: function (settings, original) {
  var value =  "<span class=fn>" + $("#fn_").val() + '</span>' + '<span class=spouse>' + $("#spouse_").val() + '</span>' + '<span class=bday>' + $("#bday_").val() + '</span>' + '<span class=wday>' + $("#wday_").val() + '</span>' +'<span class=dday>' + $("#dday_").val() + '</span>';
      $("input", this).val(value);
  }

});

Answer

Jakub Hampl picture Jakub Hampl · Dec 4, 2010

Create an element, put it into that element with innerHTML and select them out with querySelector.

So assuming you wanted to use just plain old js:

el = document.createElement('p');
el.innerHTML = '<span class="fn" id="fn1">Matthew</span> ... <span class="dday" id="dday1">2000</span>'
el.querySelector('.fn').innerText // = 'Matthew'
el.querySelector('#fn1').outerHTML // = "<span class="fn" id="fn1">Matthew</span>"

Which translates almost directly into jQuery:

el = $('<p />').html('<span class="fn" id="fn1">Matthew</span> ... <span class="dday" id="dday1">2000</span>');
el.find('.fn').text() // = 'Mathew'