freddylindstrom
freddylindstrom

Reputation: 431

HTML attribute namespace

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?

Upvotes: 6

Views: 2851

Answers (1)

Alohci
Alohci

Reputation: 82976

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.

Upvotes: 8

Related Questions