Here is one way you can quickly convert a raw html string (provided it is complete in it's representation of the elements within the string) to an xml object and then can traverse it just like any other xml object, but note it's not directly transferable back to html, you would still need to run through the xml elements and make copies of them as DOM objects, but for what it's worth:
Code:
<script type="text/javascript">
//requires a string of xml text as the txt argument,
//returns an xml object identical to what would be returned via ajax as responseXML
function parseXMLString(txt) {
var i, parser,
w = window,
ieParserTypes = [
"Msxml2.DOMDocument.6.0",
"Msxml2.DOMDocument.5.0",
"Msxml2.DOMDocument.4.0",
"Msxml2.DOMDocument.3.0",
"Msxml2.DOMDocument.2.0",
"Microsoft.XMLDOM" //this ones supposedly the same as trying item 5 (version 2.0), but oh well, wanted to keep it
];
if (w.DOMParser) {
return new w.DOMParser().parseFromString(txt,"text/xml");
} else if (w.ActiveXObject) {
for (i = 0; i < ieParserTypes.length; i++) {
try{
parser = new w.ActiveXObject(ieParserTypes[i]);
break;
} catch (er) {}
}
parser.async = false;
parser.loadXML(txt);
return parser;
}
}
var str = '<select id="thisIsSelectId"><option value="opt0">option 0</option>';
str += '<option value="opt1">option 1</option>';
str += '<option value="opt2">option 2</option></select>';
var strToXmlObject = parseXMLString(str);
var selectId = strToXmlObject.getElementsByTagName('select')[0].getAttribute('id');
alert(selectId);
var options = strToXmlObject.getElementsByTagName('option');
alert("options.length = "+ options.length +"\noptions[1].value = "+ options[1].getAttribute('value'));
</script>
Bookmarks