Parsing XML with namespaces using jQuery $().find

I'm trying to get the contents of a XML document element, but the element has a colon in it's name.

This line works for every element but the ones with a colon in the name:

$(this).find("geo:lat").text();

I assume that the colon needs escaping. How do I fix this?

Answers:

Answer

Use a backslash, which itself should be escaped so JavaScript doesn't eat it:

$(this).find("geo\\:lat").text();
Answer

That isn't just an ordinary element name. That's a qualified name, meaning that it is a name that specifically refers to an element type within a namespace. The element type name is 'lat', and the namespace prefix is 'geo'.

Right now, jQuery can't deal with namespaces very well, see bug 155 for details.

Right now, as a workaround, you should be able to select these elements with just the local name:

$(this).find("lat").text();

If you have to distinguish between element types with the same local name, then you can use filter():

var NS = "http://example.com/whatever-the-namespace-is-for-geo";
$(this).find("lat").filter(function() { return this.namespaceURI == NS; }).text();

Edit: my mistake, I was under the impression that patch had already landed. Use Adam's suggestion for the selector, and filter() if you need the namespacing too:

var NS = "http://example.com/whatever-the-namespace-is-for-geo";
$(this).find("geo\\:lat").filter(function() { return this.namespaceURI == NS; }).text();
Answer

if you have a jquery selector problem with chrome or webkit not selecting it try

$(this).find('[nodeName=geo:lat]').text();

this way it works in all browsers

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.