convert HTML DOM structure to JSON

后端 未结 5 1509
太阳男子
太阳男子 2020-12-05 21:27

I have wasted so much time on this..the recursion part is quite illusive.
for a given HTML structure, of unknown depth, I need to convert to JSON.
(I use this

5条回答
  •  春和景丽
    2020-12-05 21:44

    If you can convince yourself to using jQuery, try this:

    function helper(root) {
      var result = {};
    
      $('> ul > li > span', root).each(function () {
        result[$(this).text()] = $(this).hasClass('title') ? helper($(this).parent()) : $(this).next('input').val();
      });
    
      return result;
    }
    
    console.log(helper('body'));
    

提交回复
热议问题