I would like to take a string and treat it as XML. Then I will be able to query with DOM via the jQuery.find. Everything was working fine in Firefox, but I realized this is not working in IE.
I am doing this:
var t = "<div><outer><inner>abc</inner><inner>def</inner></outer></div>";
alert("[" + $(t).find("outer").html() + "]");
In Firefox 3 it prints:
[<inner>abc</inner><inner>def</inner>]
In IE 7 it prints:
[]
Any workarounds for getting this to work across browsers?
Thanks.
There are a 2 ways to approach this.
Would it be possible to store the XML as JSON (I would assume it would be)? For instance, in PHP, you can convert XML to an Array or Object and then convert that into JSON with json_encode
. You could then echo that out as a javascript variable like so:
In PHP:
<?php
$xml = "<div><outer><inner>abc</inner><inner>def</inner></outer></div>";
$xml_object = simplexml_load_string(xml);
$json = json_encode($xml_object);
?>
<script language="javascript">
$(function() {
// eval() is okay to use if you know where the JSON is
// coming from (and, of course, you do...)
var data = eval('<?php echo $json; ?>');
$(document).data('myapp.data',data);
});
</script>
And now, whenever you need to access that data, you can just get it like so:
function some_function() {
var data = $(document).data('myapp.data');
$.each(data.div.outer,function() {
// Would alert 'abc' then 'def'
alert(this.inner);
});
}
I hope all that makes sense. At least you won't have to worry about XML anymore on the client side. Of course, if you absolutely need to, I've found that this has worked for me in the past:
var xml = "<div><outer><inner>abc</inner><inner>def</inner></outer></div>";
var $xml = $('<div />').append(xml);
alert("[" + $xml.find("outer").html() + "]");
Edit I modified my code to use the actual XML you provide--not sure where I mixed up there (must've grabbed the snippet from someone else's answer on accident). You should really give my first suggestion a shot--it should work.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With