views:

667

answers:

2

I have the following XHTML:

<span id="myid" cus:att="myvalue" xmlns:cus="http://mycompany.com/customnamespace"&gt;
</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  A: 

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')
annakata
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.
Bogdan Constantinescu
My problem wasn't getting the element but I will add the id to the question.
tpower
@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
@annakata Sure, I didn't say you were wrong, but right about now the answer is very good. +1 :)
Bogdan Constantinescu
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.
tpower
you can of course do some nasty trawling like "var e = document.getElementById("foo"); for(var x in e.attributes) { if(x.match(/att$/)) { alert(e.getAttribute(x)); } }", and it's likely jQuery et al have abstractions which wrap this for you
annakata
+1  A: 

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

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