I'm working on a Chrome extension which, under certain conditions, performs a $.ajax()
request and then uses information of specific elements in the returned HTML
. For now, I'm simply trying to have it access the specific element and log it to the console to ensure it works correctly.
To start, I am fairly certain the HTML
is successfully retrieved. When I log the result directly, the output is identical to the result when I view the page source in Chrome. I've also tried using $.parseHTML()
which, when logged, gives me an array of top-level children. Using selectors returns an array of the immediate children matching the selector, but they do not work for elements which are children of these children (and so on).
I've looked at several posts already, and tried a variety of things such as using $(<selector>,<context>)
, $(<result>).filter(<selector>)
, and $(<result>).find(<selector>)
to no avail. Every time I try to log these I end up with an object of length 0
.
$.ajax({jsonp: false, dataType: "html",url: getUWFlowLink($(this).attr('href')), success: function(siteHTML){
console.log($("p.description",siteHTML));
console.log($("p.description",$.parseHTML(siteHTML)));
console.log($(siteHTML).find("p.description"));
console.log($($.parseHTML(siteHTML)).find("p.description"));
console.log($(siteHTML).filter("p.description"));
console.log($($.parseHTML(siteHTML)).filter("p.description"));
}});
All of these logs simply return objects with 0
length. Trying to log the .html()
results in an output of undefined
, and trying to log the .text()
results in an empty string for output. A sample page, for reference is here. The element I am trying to access is the description blurb at the top ("Chemical principles with applications...") and its location in the HTML (a few levels deep) can be found by inspecting the element.
Try something like this
jQuery requires a tree structure to traverse and perform its operations. Directly trying to use
.find()
without having a root element would not work. In the above case$('<div/>')
would be the root element and by appending the result, jquery would be above to traverse it and findp.description
.