Why are anchor nodes pointing to href and text nodes pointing to [object]?

Consider following html code
<p id=“oliver”>
<a id=“oliver1” href=“/oliver1/”>Oliver Twist 1</a>
<a id=“oliver2” href=“/oliver2/”>Oliver Twist 2</a>
<a id=“oliver3” href=“/oliver3/”>Oliver Twist 3</a>
<a id=“oliver4” href=“/oliver4/”>Oliver Twist 4</a>
</p>

Applying JavaScript to above html as following:

var getEle = document.getElementById(“oliver”);
var allP = getEle.childNodes;
for(i in allP) {document.write(i + ": " + allP[i] + “<br>”); }
Output:
length: 8
0: file:///F:/oliver1/
1: [object]
2: file:///F:/oliver2/
3: [object]
4: file:///F:/oliver3/
5: [object]
6: file:///F:/oliver4/
7: [object]

Why are anchor nodes pointing to href and text nodes pointing to [object]? As anchor and text both are objects therefore all outputs from indices 0 to 7 should be [object].
Can you please tell me why array allP[0] references href’s value instead of anchor tag?

Thank you Raffles for your explanation.:slight_smile:

I will make note of it as some kind of exceptions:D

Regarding your first post, you’re right in that it should say something different, like [object HTMLAnchorElement], which is what it would do for other elements, like P or DIV. But it seems like the browser makes things “easier” (actually, causing confusion) by outputting the href attribute as its textual identity. But they are both objects, the anchors Element nodes, the other Text nodes. You can query them using the nodeType property.

Thank you so much DogFang!!!

I realized my mistake there in the code.:smiley:
It was a syntax error in the for-loop structure. This was even not caught my JavaScript Editor.

Thanks for you help!!! :):):):slight_smile:

function aListener(tagName, evt)
{
var Tag = document.getElementsByTagName(tagName);
var Evnt = "on" + evt;
for (var i=0;i<Tag.length;i++)
{
if (Tag[i].addEventListener)
{
Tag[i].addEventListener(evt, fun, false);
}
else if (Tag[i].attachEvent)
{
Tag[i].attachEvent(Evnt, fun);
}
}

}

Could you please explain why following code works if I call function “aListener” only one time?

For example:

<HTML>
<HEAD><TITLE>NEW METHOD</TITLE></HEAD>
<BODY>

<a href=“http://www.google.com”>Click this Anchor link</a>
<p>Click this paragraph</p>

<SCRIPT LANGUAGE=“JavaScript”>
<!–
function fun()
{
alert(“Found”);
}

function aListener(tagName, evt)
{
	var Tag = document.getElementsByTagName(tagName);
	var Evnt = "on" + evt;
	for (var i=0;Tag.length;i++)
	{
		if (typeof Tag[i].addEventListener !='undefined')
		{
			Tag[i].addEventListener(evt, fun, false);
		}
		else if (typeof Tag[i].attachEvent != 'undefined')
		{
			Tag[i].attachEvent(Evnt, fun);
		}							
	}
			
}

aListener(‘a’, ‘click’);
aListener(‘p’, ‘mouseover’);
//–>
</SCRIPT>
</BODY>
</HTML>

When I call the function aListener for two times for different events and different nodes, the above code works for click event only. Could you please elaborate on this?