We help IT Professionals succeed at work.

Javascript DOM element comparison

oggiemc used Ask the Experts™
Hello all,

I have a piece of java code which gets all html elements from a page.. I then want to do a comparison between these elements to see if one is the same as another..My code is like:

var elementArray = documentNode.getElementsByTagName(selectOption); // Returns inputs, tables, links etc..

The code that checks for equality is then:

if (elementArray[count-1] == elementArray[count])

The problem is this code evalutes to false, even if there are 2 input elements..Can someone tell me what im doing wrong here? Thanks
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Does it work if you do this instead?

if (typeof(elementArray[count-1]) == typeof(elementArray[count]))
A tip is to use alert to find the buggy code.


and have a look for yourself what values are returned.
Also try using === instead of ==


hi walkman,

All the different elements are of typeof object so its no good for comparing different elements..
Shouldnt it say document.documentNode?
If you simply want to check that elements are of the same html element type, you could try using the nodeName property.

if (elementArray[count-1].nodeName == elementArray[count].nodeName)

Open in new window


No, that is a variable defined by me..

that works thanks..Any ideas why original code didnt work? I assume its because it was comparing objects while yours compares strings??

As far as I know, when comparing objects in javascript, they are only considered equal if the 2 variables simply refer to the exact same instance of the object. It doesn't do any data comparison, so even if the data is the same, they still aren't equal. If you want to compare separate instances of objects (eg. different html elements) according to some data attribute (eg. tag type), you'd need to compare the relevant property directly.


ok..thanks, i dont need to go into that level of detail.. i just needed to compare tags and ur answer covers that easily..Thanks again,