开发者

getElementsByTagNameNS in (X)HTML documents

开发者 https://www.devze.com 2023-01-18 01:45 出处:网络
I have a question on Javascript and DOM; shouldn\'t the following code retrieve the three foo:bar elements in the body? The alert window displays zero. It doesn\'t work in any browser I have (not even

I have a question on Javascript and DOM; shouldn't the following code retrieve the three foo:bar elements in the body? The alert window displays zero. It doesn't work in any browser I have (not even Chrome Canary). Thank you for helping, have a nice weekend.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml开发者_如何学Gons:foo="http://example.com">
    <head>
        <title>Hello!</title>

        <script type="text/javascript">
        function bodyLoad() {
            var extElements = document.getElementsByTagNameNS('http://example.com', 'bar');

            alert(extElements.length);
        }
        </script>
    </head>

    <body onload="bodyLoad();">
        <foo:bar>First Foo-Bar</foo:bar>
        <foo:bar>Second Foo-Bar</foo:bar>
        <foo:bar>Third Foo-Bar</foo:bar>
    </body>
</html>


You are likely serving the document with the wrong content type. The browser has to treat it as XML for namespaces to be recognized, so you need to use application/xhtml+xml or another XML content-type, and not text/html.

As an aside, your Doctype is wrong. If you want to use a DTD, then you will need one that includes the elements you are using from the foo namespace. If you don't, then just get rid of the Doctype — it has no bearing on rendering mode in XML documents (again, text/html documents are treated as tag soup, not XML).

0

精彩评论

暂无评论...
验证码 换一张
取 消