0

I am trying to extract a user input html data and store them in an object or array

The source of html could be as following

begin <em>texts</em>
    description texts here

<table>
   <tr><td>cell 1<td><td>cell2</td></tr>
   <tr><td>cell 3<td><td>cel4</td></tr>
</table>

<em>second<em> part texts

<table>
   <tr><td>cell 5<td><td>cell6</td></tr>
   <tr><td>cell 7<td><td>cel8</td></tr>
</table>

I need to be able to store the following things.

all the texts outside of table and the cell data in table. they need to be in order.

I have tried

var data = [];
sourceHtml.contents().each(function(){
    if($(this).is('table')){
          var table = $(this)
          var rows = 'rows:' + $('tr', table).length;
          var column ='column:' + $('td', table).length / $('tr', table).length;
          //i need to get the table columns and rows counts
          data.push(rows)
          data.push(column)

          table.find('td').each(function(){
              data.push($(this).text().trim());
          })
        }else{
          data.push($(this).text().trim());
        }
 })

The above will only give me all the texts in the sourceHtml but lose all the markup for my texts. Are there anyway to maintain the html markup while getting texts of my data? Thanks so much for the help!

2
  • do you have only 1 table? Commented Jul 19, 2013 at 20:08
  • Instead of using .text() use .html() Commented Jul 19, 2013 at 20:08

2 Answers 2

1

Instead of $(this).text().trim() use $(this).html()

Hope this helps

Sign up to request clarification or add additional context in comments.

Comments

1

Use .html() instead of .text() to get an element's HTML markup content instead of text node content.

http://api.jquery.com/html/

1 Comment

thanks, but for some reasons, all the texts return null when I change }else{ data.push($(this).html().trim()); } +1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.