Selecting just specific part of HTML with XMLHttpRequest?

1.6k Views Asked by At

I currently download an HTML from a website and I'm using "responseText" to get the HTML code, now I only want a specific part of it. How do you select a specific part of the HTML code with XMLHttpRequest? I already research doing it using Xpath or querySelectorAll, how do I do this practically and easily? Let say from the HTML code you wan't to select only --> div where id="home-members".

Thanks in advance!

This is the codes:

foobar.com/index.html:

..........
.....
<body>
..........
<div id="home-members">
    ........
    .....
</div>
....
</body>

My Traversal code:

<script>
$.ajax({
   url: "http://foobar.com/index.php",
   cache: false
}).done(function( html ) {
   var partial = $(html).find("home-members");
   $("#results").append( partial);
})
</script>

<body>
    <div id="results"></div>
</body>
3

There are 3 best solutions below

0
On

I recommend use HtmlAgilityPack for this.

3
On

Use jQuery to search the returned html. Something like:

$.ajax({
  url: "test.html",
  cache: false
}).done(function( html ) {
  var partial = $(html).find("div.dynamic-wrap.sidebar-wrap.clearfix");
  $("#results").append( partial);
});
0
On

mm if i don't understand wrong...

responseText is a string so you could select parts of it using regEx but i think it could be not easy and hacked.

another solution could be.. putting the response text in a div using InnerHTML, so you can use standard javascripts selectors to take various elements. something like..

document.getElementById('structural_div').innerHTML = responseText;

var what_you_need = document.getElementById('structural_div').getElementById('id_of_element_you_need').className

instead of getElementById('id_of_element_you_need') you can get the element in the way you want, by class name, by tag name etc..

Hope to have helped you :)