I am making an ajax call and I get the content from responseText
.
I confirm by using alert
that inside, the responseText
contains the entire page as a string
.
That's fine. Now I need to extract specific contents from the string by converting it to DOM and using getElementsByTagName
, getElementsByName
etc...
My problem is that none of these seems to work.
I've read many references on using responseXML
instead of responseText
but this gives me back null
.
So, by sticking to responseText
, how can i get the specific elements that I want?
For instance if my response contains the following:
<html>
<head>....</head>
<body>....
.....
<table>
<tr>
<td>sometext</td>
<td>someothertext</td>
</tr>
<tr>
<td>sometext</td>
<td>someothertext</td>
</tr>
<tr>
<td>sometext</td>
<td>someothertext</td>
</tr>
</table>
<div> somediv </div>
</body>
</html>
how can I access the second row of the table and its value? Or the div etc.. so, now in my actual html, i have sth like this
<html>
<head>.....</head>
<body>
<table><tr><td id="test">Test</td></tr></table>
</body>
</html>
i want the extracted element/value to be parsed inside the table of my actual html..
document.getElementById('test').innerHTML = the_extracted_elements_from_responseText
You need to use a DOMParser
on the html and use DOM traversal methods on the resulting document to return the desired node(s).
var parser=new DOMParser();
var xmlDoc=parser.parseFromString(responseText,"text/xml");
var tds = xmlDoc.getElementsByTagName("td");
Note that IE would require new ActiveXObject("Microsoft.XMLDOM");
instead.