Names and IDs of Elements

An element in a web page could be represented either by a name or by an id or by both. For example:

<div name="divName" id="divID">
div content
</div>

If the element is part of a FORM -the name of the element is sent to server along with the value of the element when the form is submitted. Therefore name is important for the name-value pairing in the query string that goes to server.

The ID of the element is generally used to refer to the element in client-side scripts (like JavaScript). This is accomplished by getElementById() method of the document object in the DOM model. For example:

var foo = document.getElementById('elementID').value;

When we assign names and IDs to the elements -it is quite tempting to keep them same (especially in large applications where either we run out the logical/sensible names or find it difficult to keep track of them), like:

<div name="foobar" id="foobar"></div>

This practice is mostly harmless -but I have noticed that it sometimes causes problems in context of AJAX (especially in IE). A few of my AJAX scripts which worked fine in FF; did not work in IE and Safari. Eventually the problems were solved when I made the names and IDs of the used elements different. I think this problem is application specific and will not appear in every AJAX script. However, I guess it is a good practice to keep the names and IDs different. To get around the issue of running out of the sensible names -I just suffix “ID” to the id of the element while keeping rest of the string same as that of it’s name. e.g.

<div name="foobar" id="foobarID"></div>

One Comment

  1. Posted August 3, 2008 at 12:42 am | Permalink

    Tahnks for posting


Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*