Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I parse a Ajax html GET response in jQuery?

I'm tempering with a Chrome Extension where I use an Ajax-request to get HTML from a requested URL. This works, but I want to get all the text values some certain elements. By example, everything with the class .heading-bold

script.js

$.ajax({
        url: "http://page.com/page.html",
        type: "GET",
        dataType: "html",
          success: function(data) {
              console.log($(data).filter( '.heading_bold' ).text()); 
          }
    });

Response HTML

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head><title>Beerpong</title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <meta http-equiv="Expires" content="0" />
    <meta http-equiv="Pragma" content="no-cache" />
    <meta http-equiv="Cache-Control" content="no-cache" />
    </head>
     <body>
        <div id="table-container">
            <table>
               <tbody>
                  <tr>
                   <td><div class="heading_bold">Beerpong</div></td>
                  </tr>
                </tbody>
            </table>
        </div>
     </body>
    </html>

Logging it to the console works just fine. This is my output:

Uncaught Error: Syntax error, unrecognized expression: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0....

Why? Why won't it just console.log my desired values?

like image 868
Jack Avatar asked Dec 02 '22 20:12

Jack


1 Answers

If you are using jquery 1.9, do:

...
success: function(data) {
   var html = $.parseHTML(data); 
   console.log($(html).find( '.heading_bold' ).text()); 
}
..

Because as per jQuery 1.9:: HTML strings passed to jQuery() that start with something other than a less-than character will be interpreted as a selector. Since the string usually cannot be interpreted as a selector, the most likely result will be an "invalid selector syntax" error thrown by the Sizzle selector engine. Use jQuery.parseHTML() to parse arbitrary HTML.

like image 131
Sudhir Bastakoti Avatar answered Dec 11 '22 17:12

Sudhir Bastakoti