Reputation: 43
I am making a GET call to the server and it returns a String of HTML. I want to parse this HTML and only get the HTML with the id 'container'.
Here is my code:
$("#name").click(function() {
$.ajax({
type : 'GET',
url : "/",
dataType : 'text',
success : function(data) {
var object = $('<div/>').html(data).contents(); //Convert the String into an object.
var container = object.find('container'); //This successfully gets the object with the id 'container'
console.info(container.html()); //Here is where I want to output just the HTML of the container.
},
error : function(data) {
console.error("Error getting homepage");
}
});
return false;
});
I want to just output the HTML that has the id 'container'. Right now it is outputting nothing. I don't think I am doing this in the best way.
ALSO: I am going to be loading the HTML into another element on the page.
Upvotes: 1
Views: 3320
Reputation: 43
I was able to accomplish what I wanted with the following:
$("#name").click(function() {
$.ajax({
type : 'GET',
url : "/",
dataType : 'text',
success : function(data) {
var parser = new DOMParser();
doc = parser.parseFromString(data, "text/html");
var remainder = doc.getElementById("main-content").innerHTML;
$("#r-div").replaceWith("<div id=\"main-content\">" + remainder + "</div>");
},
error : function(data) {
console.error("Error getting homepage");
}
});
return false;
});
This gets a HTML response then extracts "main-content" div and replaces "r-div" in the current page with the HTML
Upvotes: 3
Reputation: 24
This is what I used in my own code:
var xhr = new XMLHttpRequest();
var url = "http://....";
xhr.open("GET", url, true);
xhr.send();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
html = $.parseHTML( xhr.responseText );
var container = $("#container", html);
}
}
Upvotes: 0