Welcome to WebmasterWorld Guest from

Forum Moderators: httpwebwitch

Message Too Old, No Replies

Get Attributes with javascript

Problem accessing attributes with javascript



6:10 am on Jun 13, 2008 (gmt 0)

5+ Year Member

Hi I'm hoping someone can help me here i'm trying to access the attributes in the following XML file named data.xml:

<?xml version="1.0" ?>
<employee id="001" sex="M" email="Prem@igy.com">Premshree Pillai
<employee id="002" sex="F" email="KS32@alltoeasy.net">Kumar Singh
<employee id="003" sex="M" email="Ran Kapoor">Ran Kapoor

i can load the file and i can get to the employee element but when i try to get the attributes i get the following error in firebug:

xmlDoc.getElementsByTagName("employee").attributes has no properties

here is my javascript code:

var xmlDoc=null;
if (window.ActiveXObject){//IE code
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
else {// code for mozilla, firefox, opera, etc.
xmlDoc.onload = printData;

//displaying the results
function printData(){
var employeeNode = xmlDoc.getElementsByTagName("employee");
var idNode = xmlDoc.getElementsByTagName("employee").attributes.getNamedItem("id").value;
var sexNode = xmlDoc.getElementsByTagName("employee").attributes.getNamedItem("sex").value;
var emailNode = xmlDoc.getElementsByTagName("employee").attributes.getNamedItem("email").value;
var imageNode = xmlDoc.getElementsByTagName("image");

please help


1:13 pm on Jun 13, 2008 (gmt 0)

WebmasterWorld Administrator httpwebwitch is a WebmasterWorld Top Contributor of All Time 10+ Year Member

getElementsByTagName("employee") should return an array of all the matched elements. An array doesn't have any attributes, so try this instead:



1:15 pm on Jun 13, 2008 (gmt 0)

WebmasterWorld Administrator httpwebwitch is a WebmasterWorld Top Contributor of All Time 10+ Year Member

I didn't test this, but it's probably closer to what you want. note the for loop that iterates through the array constructed by getElementsByTagName

//displaying the results
function printData(){
var employeeNodeArray = xmlDoc.getElementsByTagName("employee");
for(employeeNode in employeeNodeArray){
var idNode = employeeNode.attributes.getNamedItem("id").value;
var sexNode = employeeNode.attributes.getNamedItem("sex").value;
var emailNode = employeeNode.attributes.getNamedItem("email").value;


Featured Threads

Hot Threads This Week

Hot Threads This Month