0

I'm using jQuery to parse XML which is retrieved via ajax, however I have found a problem/bug with using the actual XML input.

Consider the following example:

var $line = $('<example dir="value">Example Text</example>'), dir = $line.attr("dir");
console.info("dir: ", dir);

This example should return 'value' instead it returns an empty string. Tried the above code with a different attribute name and it returns the correct value.

Is 'dir' an invalid attribute? Or is this a bug in jQuery? Just wondering...

2
  • Actually your exact code works for me. Commented Aug 26, 2010 at 10:35
  • Maybe a different jQuery version? I'm using 1.4.2 Commented Aug 26, 2010 at 10:45

3 Answers 3

1

dir = $line.get(0).getAttribute("dir") works just fine.

Going to post this issue in the jQuery discussion page.

Sign up to request clarification or add additional context in comments.

Comments

1

$(markup) parses as HTML, not XML, giving you an HTMLUnknownElement with tagName example. dir is an existing HTML attribute which may only have the values rtl or ltr. Anything else is ignored, which is why the custom attribute isn't readable under the DOM property dir.

(Contrary to what you might expect from the name, jQuery's attr() method actually usually represents DOM property access and not HTML attribute access, even though it allows the HTML attribute names to be used as aliases.)

You may have further problems in IE which doesn't much like custom elements being dropped into HTML.

Getting a browser to parse XML isn't quite as simple as you might think. Having an XML document returned by XMLHttpRequest (ajax()) works everywhere, so if you can, move the XML into an AJAX response.

Otherwise, getting an XML parser to read a string isn't the same on all browsers (and older browsers can't do it at all). On IE you have to use a new ActiveXObject('Microsoft.XMLDOM'); on other browsers you often get a new DOMParser(); failing that, you can try to document.implementation.createDocument().loadXML().

Comments

0

because i dont think it gets parsed, try this

var $line = $('<example></example>').attr('dir','value').value('Example Text');

1 Comment

Tried the above with a slight difference: var $line = $('<example></example>').attr('dir','value').val('Example Text'); But the result is the same. I Know that the example I give is being parsed because changing to: var $line = $('<example direction="value">Example Text</example>') would work. However I cannot change the ajax retrieved XML so have to stick with the 'dir' attribute.

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.