The createElement() method is used to create a new element of the type specified by the tag name.
Syntax for createElement() method
createElement(name);
Where,
- name is the name of the element node to be created.
In the example below, an element called ‘school’ and its text node is created and added to the XML document. The createElement() returns the element node created.
Example with createElement() method
element.xml
<?xml version="1.0"?>
<students>
<name>Roshni</name>
<class>3rd grade</class>
</students>
element.html
<!DOCTYPE html>
<html>
<body>
<script>
function loadFile(name){
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET",name,false);
xmlhttp.send();
return xmlhttp.responseXML;
}
xmlDoc = loadFile("element.xml");
xd = xmlDoc.documentElement;
newEle = xmlDoc.createElement("school");
newTxt = xmlDoc.createTextNode("RobinHood School of Learning");
newEle .appendChild(newTxt);
d = xmlDoc.getElementsByTagName("students")[0];
d.appendChild(newEle);
d = xmlDoc.getElementsByTagName("students");
for(j=0; j<d.length; j++){
c = d[j].childNodes;
for(i=0; i< c.length; i++){
if(c[i].nodeType != 3){
document.write("NodeName : " + c[i].nodeName);
document.write(" NodeType : " + c[i].nodeType);
document.write(" NodeValue : " + c[i].childNodes[0].nodeValue + "<br/>");
}
}
}
</script>
</body>
</html>
Output to the example above will be:
NodeName : name NodeType : 1 NodeValue : Roshni
NodeName : class NodeType : 1 NodeValue : 3rd grade
NodeName : school NodeType : 1 NodeValue : RobinHood School of Learning
Comments
No comments have been made yet.
Please login to leave a comment. Login now