2

Can anyone explain this strange behaviour in jQuery? I'm using version 1.5.2.

var myxml = '<photo><Point srsName="EPSG:4326"><coordinates>0.153933,52.204674</coordinates></Point><id>24917</id><latitude>52.204674</latitude><longitude>0.153933</longitude><feature>3</feature><caption>No parking.</caption><url>http://www.google.co.uk</url><imageUrl>http://www.google.co.uk</imageUrl><thumbnailUrl>http://www.google.co.uk</thumbnailUrl><thumbnailSizes>60|120|150|180|200|250|300|350|400|400|425|450|500|640</thumbnailSizes></photo>';
console.log($(myxml).find('latitude').text());     
console.log($(myxml).find('caption').text());

latitude prints the correct value, but caption is an empty string.

I've tried using nodeName as well, but I get the same result.

Any ideas? Thanks!

UPDATE: I've also made a jsFiddle to show the behaviour: http://jsfiddle.net/w8Z7z/

3 Answers 3

1

You aren't telling jQuery you're working with XML. caption is an HTML tag and reserved word, so it is getting confused. You need to use $.parseXML():

var myxml = '...(all that xml)...',
    xmlDoc = $.parseXML( myxml ),
    $xml = $( xmlDoc );
console.log($xml.find('caption').text());
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! Although I'm now getting $.parseXML is not a function - any ideas?
@simon: Are you using jQuery 1.5+ ? This was added in 1.5.
1

Caption appear to be a reserved word. So, if yo use for example captionX works.

Try with other nodeName.

var myxml = '<photo><Point srsName="EPSG:4326"><coordinates>0.153933,52.204674</coordinates></Point><id>24917</id><latitude>52.204674</latitude><longitude>0.153933</longitude><feature>3</feature><captionX>No parking.</captionX><url>http://www.google.co.uk</url><imageUrl>http://www.google.co.uk</imageUrl><thumbnailUrl>http://www.google.co.uk</thumbnailUrl><thumbnailSizes>60|120|150|180|200|250|300|350|400|400|425|450|500|640</thumbnailSizes></photo>';
console.log($(myxml).find('captionX').text());
console.log($(myxml).find('latitude').text());

Comments

1

If you parse the xml first and then pass that to jquery it works:

http://jsfiddle.net/w8Z7z/2/

var xmldoc=$.parseXML(myxml);  
alert($(xmldoc).find('caption').text());

1 Comment

Excellent. I sort of went down that path (putting an XML declaration in, which didn't work), but this is a much better approach.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.