Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between setAttribute and setAttributeNS(null,

What is the difference between calling setAttribute and setAttributeNS with null as the namespace parameter?

Also is there an issue with using getAttribute() and then setAttributeNS ?

like image 935
SPlatten Avatar asked Jan 28 '16 09:01

SPlatten


People also ask

What is setAttributeNS?

setAttributeNS() setAttributeNS adds a new attribute or changes the value of an attribute with the given namespace and name.

Why is setAttribute not working?

The "setAttribute is not a function" error occurs for multiple reasons: calling the setAttribute() method on a value that is not a DOM element. placing the JS script tag above the code that declares the DOM elements. calling the setAttribute method on a jQuery object (should use attr() instead).

What method allows us to add an attribute to a DOM element?

The setAttribute() method sets a new value to an attribute.


2 Answers

setAttribute() is a DOM 1 function. setAttributeNS() is a DOM 2 function that resolves the problem of conflicting tag or attribute names by specifying the xmlns namespace that should apply to the tag/attribute in the first argument.

If an attribute does not have a defined namespace prefix, the first argument must be null. You could use setAttribute() but for consistency it is advisable to stick to setAttributeNS(). See:

https://developer.mozilla.org/en/docs/Web/SVG/Namespaces_Crash_Course#Scripting_in_namespaced_XML

"However, note carefully: the Namespaces in XML 1.1 recommendation states that the namespace name for attributes without a prefix does not have a value. In other words, although the attributes belong to the namespace of the tag, you do not use the tag's namespace name. Instead, you must use null as the namespace name for unqualified (prefixless) attributes."

like image 157
Chris Robinson Avatar answered Oct 18 '22 08:10

Chris Robinson


Here's an explanation in English, from the MDN docs:

// Given:
//   <div id="div1" xmlns:special="http://www.mozilla.org/ns/specialspace"
//     special:specialAlign="utterleft" width="200px" /> 

d = document.getElementById("div1"); 
d.removeAttributeNS("http://www.mozilla.org/ns/specialspace", "specialAlign"); 

// Now:
//   <div id="div1" width="200px" />

So from this, it appears that xmlns:special="http://www.mozilla.org/ns/specialspace" is a declaration of the namespace special, which is then used to contextualize special:specialAlign.

like image 1
Andrew Avatar answered Oct 18 '22 08:10

Andrew