1

I am using a JQuery function to retrieve a string containing some HTML code and process it locally. The string is:

var return_data = '<div><tr><td>blah</td><td>more blah</td></tr><tr><td>blah</td><td>more blah</td></tr><tr><td>blah</td><td>more blah</td></tr><span id="morerows">1</span></div>';

(I understand <tr> should come inside <table> and not inside <div> but this is how I need the input for some reason and that should be inconsequential to the issue at hand.) What I need is to loop through each <tr> and output the contents to the console. I am trying this:

$(return_data).find("tr").each(function(){
  var myData = $(this).html();
  console.log(myData);
});

But the above does nothing; no output on the console. Just to be sure, I changed the console.log() input to simply "hello" and turns out, the control isn't even entering the loop. What could possibly be causing this?

5
  • What shows console.log($(this));? Commented Jan 16, 2016 at 7:49
  • No point doing console.log($(this)) if the loop isn't being entered to begin with. That's what I said in the question as well. Even a console.log("hello") didn't execute. Commented Jan 16, 2016 at 7:51
  • 1
    the trs are ignored because they make no sense in a div. Commented Jan 16, 2016 at 7:51
  • Nope, they shouldn't be ignored because to JQuery, they should just be another element within an element. Commented Jan 16, 2016 at 7:52
  • A console.log($(return_data)); shows that there is only text and the span in there. Commented Jan 16, 2016 at 7:53

2 Answers 2

1

You may need the following. Wrap trs with a table and loop through the trs instead of div.

var return_data = '<div><table><tr><td>blah</td><td>more blah</td></tr><tr><td>blah</td><td>more blah</td></tr><tr><td>blah</td><td>more blah</td></tr></table><span id="morerows">1</span></div>';

$(return_data).find("tr").each(function () {
    var myData = $(this).html();
    console.log(myData);
});
Sign up to request clarification or add additional context in comments.

2 Comments

I cannot use the <table> tag because I already have an existing table on page to which these rows need to be appended. That's why I am only receiving the rows from the server.
tr cannot be nested inside div. It will not even been rendered if you not use table. @TheLearner
0

you are missing <table> tag in ur html, try this fiddle

 var return_data = '<div><table><tr><td>blah</td><td>more blah</td></tr><tr><td>blah</td><td>more blah</td></tr><tr><td>blah</td><td>more blah</td></tr></table><span id="morerows">1</span></div>';

1 Comment

The <table> tag is not missing...I don't have it for a reason. Please see the edit in my question.

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.