Lionel Seguin
Lionel Seguin

Reputation: 31

What is the difference between createElement(...) and createElementNS('http://www.w3.org/1999/xhtml', ...)

I don't understand the difference between createElement(...) and createElementNS('http://www.w3.org/1999/xhtml', ...)

You can try this following code:

var element1 = document.createElement('form:form');
var element2 = document.createElementNS('http://www.w3.org/1999/xhtml', 'form:form');

console.log(element1.tagName); // FORM:FORM
console.log(element1.localName); // form:form

console.log(element2.tagName); // FORM:FORM
console.log(element2.localName); // form

I was thinking it will be the same result but not at all. Someone know why?

Upvotes: 3

Views: 576

Answers (2)

Kaiido
Kaiido

Reputation: 136866

Namespaces in markup are marked by the namespace:element syntax (or namespace:attribute for that matter) DOM methods createElementNS and setAttributeNS do not need this syntax to create elements in the given namespace, but because the markup syntax allows it, they will still recognize it and ignore it.

So that when you stringify your document, you can have

<html xmlns:form="http://www.w3.org/1999/xhtml">
  <form:form></form>
</html>

Instead of some hard to read

<html xmlns:NS0="http://www.w3.org/1999/xhtml">
  <NS0:form></form>
</html>

createElement and setAttribute methods however will not recognize this syntax, and will really create an <xmlns:form:form></form> element.

Upvotes: 1

Sami Ahmed Siddiqui
Sami Ahmed Siddiqui

Reputation: 2386

difference between the createElement and createElementNS is that you can specify the namespace URI in createElementNS whereas createElement doesn't allow that.

createElementNS can be used when you need to create a SVG from the JS. AS SVG needs the namespace URI. You can check the valid namespaces from here: https://developer.mozilla.org/en-US/docs/Web/API/Document/createElementNS#Important_Namespace_URIs

If you are creating element in HTML then you may use createElement as there is no need of the namespace in it but if you are creating HTML in XHTML then you need to use createElementNS as XHTML needs namespace with it.

Upvotes: 2

Related Questions