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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With