2

In XHTML, can onclick be used on elements outside the HTML namespace? On the code below, myFunction() fires when <p> is clicked but not when <t:div> is clicked. Can it be made to?

<html xmlns="http://www.w3.org/1999/xhtml"  
      xmlns:t="http://www.tei-c.org/ns/1.0">
<head><title>Sandbox</title></head>

<body>
<p     onclick="myFunction()">HTML p</p>
<t:div onclick="myFunction()">TEI div</t:div>

<script>
function myFunction() {
    (alert("Hello World"));
}
</script>

</body>
</html>
4
  • Code shown works fine here Commented Feb 4, 2017 at 22:46
  • 1
    @charlietfl - Thought the same initially (tested on codepen and fiddle too). However, I felt there might have been some scoop to it... and so, when tested on the local machine by saving the file as .xhtml, the behavior in question does actually come to the fore. Commented Feb 4, 2017 at 22:52
  • @JPM are you allowed to add id to the custom tags? Commented Feb 4, 2017 at 23:11
  • @DhruvSaxena, not easily. I think the problem is that onclick just doesn’t have meaning outside the HTML namespace. It’s not built-in so to speak. But maybe there is a way to invoke it explicitly. Commented Feb 5, 2017 at 0:36

1 Answer 1

3

You can't use onclick or other event handler content attributes on elements that are not HTML Elements, but you can attach an event listener in JavaScript. For example

<html xmlns="http://www.w3.org/1999/xhtml"  
      xmlns:t="http://www.tei-c.org/ns/1.0">
  <head><title>Sandbox</title></head>

  <body>
    <p onclick="myFunction()">HTML p</p>
    <t:div>TEI div</t:div>

    <script>
      function myFunction() {
        (alert("Hello World"));
      }
      document.getElementsByTagNameNS("http://www.tei-c.org/ns/1.0", "div")[0]
        .addEventListener("click", myFunction, false);
    </script>
  </body>
</html>
Sign up to request clarification or add additional context in comments.

5 Comments

Ah, right, @Alohci, that’s what I was looking for. Thanks.
Do you need the full namespace here? You can't do with just 't'?
@MrLister - Yes, you do need the full namespace. The getElementsByTagNameNS method wouldn't know how to resolve 't' to the namespace. But you can easily try this for yourself. Just create a local file with a .xhtml extension with the content from this answer and open it in your browser.
@mrlister, if the question was meant for me: yes in this application, I need real namespaces. I can't use pseudo ones.
@JPM Oh, I just wanted some clarification on what value you could use in the ...NS call.

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.