6

I have a simple html document.

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns="http://www.w3.org/2000/xmlns
      xmlns:bar="http://www.foo.com/schemas/bar">
 <head>
 </head>
 <body>
        <img src="penguins.png" bar:xwidth="300"/>
 </body>
</html>

When I inspect the attribute bar:xwidth in Chrome or Firefox debugger (or in Javascript) I would expect to find that the namespaceURI of the attribute would be "http://www.foo.com/schemas/bar", unfortunately it is null.

The issue seems to be parsing vs. programmatic construction of the element/attrs. In Javascript I can construct what I want, however any parsing, loading the above or element.innerHTML = "", yields an attribute with null namespace.

Any ideas on how to get the namespaceURI of the attribute to be correct?

1 Answer 1

7

Namespace resolution of arbitrary prefixes is an XML feature, not an HTML one. So if you served your page with an application/xhtml+xml mime type, that would cause browsers to use an XML parser, and your namespace would resolve as you intend.

Browsers' HTML parsers do not support prefix/namespace resolution at all except when parsing embedded SVG and MathML, where a very small list of attributes are "magically" converted e.g xml:lang and xlink:href. Your own namespaces are never supported.

innerHTML in an HTML document works in exactly the same way as the HTML parser does.

(Especially watch out for IE's HTML parser, which has it's own notions of what to do about elements and attributes with colons in their names. You still won't get a value for namespaceURI though)

So your only options are: (i) use application/xhtml+xml; (ii) use script to construct your namespaced attributes; or (iii) don't use namespaced attributes.

1
  • That sounds horribly complicated when all I need is a namespace to preserve the case of one attribute!
    – Michael
    Dec 30, 2022 at 18:28

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.