I'm trying to work out how to parse specific parts of a page using JQuery's AJAX method. What I'd like to do is something like this:
$.ajax({
url: "page-to-load.htm",
dataType: "html",
success: function (response) {
var html= $(response);
var content = html.find("#main");
var title = html.find("title");
var nav = html.find("ul.nav");
}
});
I know that I can load specific page parts using [container].load() but this will (as far as I understand it) create a request for each page part I want to load.
In my sample code, the html object seems to be an array of HTML elements but each of the objects returned by find() are null. The elements searched for do exist in the target page.
Am I missing something obvious or is this just not something that JQuery can handle?
This works. Use .load with the special url syntax to get the part of the page you want into a temporary div. Use the inner html from that for whatever you want.
$(function(){
var tempDiv = $("<div />");
tempDiv.load('index.html #target-element', function(){
alert(tempDiv.html());
});
});
Here is an example without the url syntax so you can work with the entire page. You can pull the title out like you are trying to do in your question...
$(function(){
var tempDiv = $("<div />");
tempDiv.load("page-to-load.htm", function() {
var content = tempDiv.find("#main");
var title = tempDiv.find("title");
var nav = tempDiv.find("ul.nav");
});
});
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