Hi all,

How do you read specific <div> tag from responsetext?
And also, is it possible to count how many <div> tag are there in responsetext?

I have been googling for quite sometime but didn't find any tutorial or explanation nor answer.

Thanks for the help.

Dani AI

Generated

A brief, modern follow-up to the approaches already shown by @Member380484 (server returns XML; parse with an XML DOM) and (inject the HTML string into a temporary element). Both approaches can work, but they have trade-offs today: responseXML only helps when the server supplies well‑formed XML/XHTML, and inserting raw HTML into a created element can be brittle and has subtle cross‑browser caveats. For reliable, maintainable parsing of an HTML fragment on the client, parsing it into a document/fragment and then using modern selectors is usually clearer.

Parsing as HTML with DOMParser (widely supported) produces a Document that supports standard APIs:

var doc = new DOMParser().parseFromString(htmlString, 'text/html');
var divCount = doc.querySelectorAll('div').length;
var node = doc.getElementById('hello'); // Document-level getElementById works reliably

If a full document is not needed, creating a fragment is lightweight and avoids touching the live page:

var range = document.createRange();
var frag = range.createContextualFragment(htmlString);
var divCount = frag.querySelectorAll('div').length;
var node = frag.querySelector('#hello'); // use querySelector on fragments/elements

Caveats and practical tips: cross-origin requests require proper CORS headers (responses will be blocked otherwise) — see CORS guidance. Scripts embedded in fetched HTML usually will not execute automatically when parsed into a detached document/fragment; executing them intentionally requires creating actual script elements and appending them. For structured data, prefer returning JSON from the server and avoid HTML parsing entirely. For reference, see the DOMParser docs and the HTML <template>/fragment parsing techniques on MDN: DOMParser and CORS.

Recommended Answers

All 5 Replies

Member Avatar for Member #380484

Okay, here's the situation ...

I thought this would be a handy thing to know and am planning on rebuilding my javascript ajax class soon anyway.

What you need to do is two-fold

1. On the server-side script that returns the results you need to set the 'Content-type" to "application/xml" -- this varies by server-side language, but in PHP it looks like this

<?php
header( 'Content-type: application/xml; charset="utf-8"');
print <<<ENDHTML
<html>
  <div>
    <div>Some block content goes here</div>
  </div>
  <div>Some more content goes here</div>
</html>
ENDHTML;
?>

Remember that xml requires a single enclosing container, so I used <html>, but it could be anything -- so long as you do NOT do this ...

<?php
header( 'Content-type: application/xml; charset="utf-8"');
print <<<ENDHTML
<div>
  <div>Some block content goes here</div>
</div>
<div>Some more content goes here</div>
ENDHTML;
?>

... which creates two root-level enclosing containers (the two <div> tags)

2. You need to grab your Ajax results as responseXML and not responseText, so ...

respXML = httpAgent.responseXML;
var divs = respXML.getElementsByTagName('div');
alert( divs.length );

... inside your Ajax function/method.

From here you can do any JavaScript DOM methods on the responseXML.

Hope this helps

Member Avatar for Member #380484

I so lied !

I can't seem to get elements of the XML using javascript DOM methods in other ways than using getElementsByTagName('tag');

but I'm still working on it, will post back here with any updates.

Ciao

Member Avatar for Member #380484

Right-O,

It's not as handy as being able to use getElementById() but this sort of thing is working and can be used to get the same results.

var divs = respXML.getElementsByTagName('div');
for ( i = 0; i < divs.length; i ++ ) {
  if ( divs.item(i).getAttribute('id') == 'last_div' ) {
    alert( divs.item(i).firstChild.nodeValue );
  } else {
    alert( divs.item(i).nodeName + ' :: ' + divs.item(i).getAttribute('id') );
  }
}

Here's my altered PHP code

<?php
header( 'Content-type: application/xml; charset="utf-8"' );
print <<<ENDHTML
<html>
  <div id="first_div">
    <div id="nested_div">Some block content goes here</div>
  </div>
  <div id="last_div">Some more content goes here</div>
</html>
ENDHTML;
?>

*Note: All of my dev was done in FF 3 and then verified in IE 7

Hope this helps

Hi,

Just for future reference. The solution for this is by using createElement("div")

First declare a variable by using createElement

var tempEle = document.createElement("div");

Then, store the responsetext into the innerHTML of that element variable

tempEle.innerHTML = html;

From there, you can use any getElement command and retrieve information from that variable.

var someID = tempEle.getElementById("hello");
alert(someID.innerHTML);

No server-side code is needed for this.

Member Avatar for Member #380484

Hi,

Just for future reference. The solution for this is by using createElement("div")

First declare a variable by using createElement

var tempEle = document.createElement("div");

Then, store the responsetext into the innerHTML of that element variable

tempEle.innerHTML = html;

From there, you can use any getElement command and retrieve information from that variable.

var someID = tempEle.getElementById("hello");
alert(someID.innerHTML);

No server-side code is needed for this.

Wanted to thank you for that piece of information. It's good to know and will certainly come in handy ...

Thanks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.