0

I have a PHP that returns an HTML snippet as string in the following format:

echo '<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>';

Now at the client, I am using JQuery (2.1.4) to extract the text of #morerows (in this example, 1) into a local var ifmore and then remove that <span> from the original HTML before further processing. Following is what I am trying for testing purposes:

var hr = createXMLHTTPRequestObject();
...
var return_data = hr.responseText;
var rdasHTML = $(return_data);
var ifmore = $('span#morerows', rdasHTML);
alert(ifmore.text());

But it only alerts blank. The HTTP request is processing fine because alert(return_data); shows the value expected. Only the extraction of the <span> element is somehow not working. Is there something I am missing out?

TheLearner
  • 2,813
  • 5
  • 46
  • 94
  • You can return only `#morerows` value (1 in your code) from server and use it, without any jquery selector. – styopdev Jan 16 '16 at 06:06
  • 2
    [Use `console.log()` instead of `alert()` for debugging.](http://stackoverflow.com/questions/8203473/why-is-console-log-considered-better-than-alert) – Michał Perłakowski Jan 16 '16 at 06:06
  • What do you mean I can only return `#morerows` value from the server? Why shouldn't one be able to just extract an element with a specific ID from a returned HTML string? I am returning `#morerows` as a separate `span` tag within the string because there's other stuff (the ``'s) I need as well. – TheLearner Jan 16 '16 at 06:09

1 Answers1

1

You have to wrap your code in a div, because now jQuery is parsing only the first tag and ignoring the rest. Your code should be:

echo '<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>';

To explain further:

console.log($("<tr><td>test</td></tr><span>test</span>")[0].outerHTML);

gives:

"<tr><td>test</td></tr>"
Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177