1

I have the following XHTML:

<span id="myid" cus:att="myvalue" xmlns:cus="http://mycompany.com/customnamespace">
</span>

Is it possible to access custom attributes with javascript? I have the element that represents the span. Doing myElement.att doesn't work, and I can't figure out how to specify the namespace?

4
  • You will need to specify whether the page is being served as text/html or application/xhtml+xml as the answer will be different. Commented Mar 26, 2009 at 9:04
  • @Alohci, I'll still be interested in seeing both answers. Commented Mar 26, 2009 at 9:16
  • In text/html the namespace is an illusion and what you have is an attribute with a colon in its name. Annakata's answer works. In application/xhtml+xml the namespace is real. I haven't tested, but I expect you will need to getAttributeNS() to access the attribute. Commented Mar 26, 2009 at 9:36
  • @Alochi, Thanks, that makes a lot of sense. Write that as an answer and it'll get a vote. Commented Mar 26, 2009 at 9:57

2 Answers 2

5

Normally speaking you can access it directly, i.e. element.attribute but the namespace slightly complicates this to:

element.getAttribute("namespace:attribute") //the nuclear x-browser option

so just to be really really clear, that'll be something like:

document.getElementById('myid').getAttribute('cus:att')
Sign up to request clarification or add additional context in comments.

6 Comments

It works, but he has to get to the element before, which doesn't have an ID, nor class, nor name. Using DOM element as "global" isn't a good practice and you might get burned.
My problem wasn't getting the element but I will add the id to the question.
@Bogdan - I'm hardly suggesting he does any global anything, I'm just providing the general form under the (correct) assumption that the OP was capable of selecting the element already
@annakata Sure, I didn't say you were wrong, but right about now the answer is very good. +1 :)
I will accept this answer but there is one thing bugging me. To do this I need to know what alias the author chose for the namespace.
|
1

There is a special version of the getAttribute method specifically designed for accessing namespaced attributes: getAttributeNS. With your example XHTML, the following JavaScript code:

document.getElementById("myid").getAttributeNS("http://mycompany.com/customnamespace", "att");

...would return "myvalue".

You can read more about the getAttributeNS method here.

Steve

2 Comments

getAttributeNS is not supported by IE
Also won't work when the document is XHTML-served-as-HTML. It takes a proper XML parser to support namespaces.

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.