Accessing the name attribute of a DIV





-10
Date Submitted Tue. Oct. 17th, 2006 3:25 PM
Revision 1 of 1
Helper jeremec
Tags Attribute | div | JavaScript | Name
Comments 7 comments
One way to group elements in HTML is to assign them a name attribute. Multiple elements can share a name, then you can easily access them as an array using the getElementsByName() method.

The problem is that some DOM parsers aren't keen on, or are ignorant to, this use of the name attribute, so a simple object.name returns undefined. In my case, it was a DIV in Firefox 1.5 that was behaving this way.

There is a simple work around for this that works in Firefox, I haven't tested it in others. It is to use the getAttribute method that is an extension of any element object.

This ability can be useful if you have a function that performs a transformation on the active element, and another transformation on closely related elements.

<div id="one" name="some_div" onclick="meFirst(this);">
   Click me!
</div>
<div id="two" name="some_div" onclick="meFirst(this);">
   Click me!
</div>
<div id="three" name="some_div" onclick="meFirst(this);">
   Click me!
</div>
 

function meFirst(object) {
  activeDiv = object.id
  divGroup = object.getAttribute("name")
  allMyDivs = document.getElementsByName(divGroup);

  for(i=0; i < allMyDivs.length; i++ ) {
    var newContent = "";
    if( allMyDivs[i].id == activeDiv ) {
      newContent = "I rule!!";
    } else {
      newContent = "Click me next!!";
    }
    allMyDivs[i].innerHTML = newContent;
  }
}
 

Jereme Claussen

Comments

Comments Correction
Wed. Oct. 18th, 2006 11:19 AM    Helper jeremec
  Comments Use classes instead
Thu. Oct. 19th, 2006 8:20 PM    Helper Thomas
Comments reason for this hack
Mon. Oct. 23rd, 2006 12:10 PM    Helper jeremec
Comments umm...
Thu. Oct. 19th, 2006 2:16 PM    Beginner jminkler
Comments try..
Thu. Oct. 19th, 2006 2:18 PM    Beginner jminkler
  Comments getElementById
Mon. Oct. 23rd, 2006 12:11 PM    Helper jeremec
Comments This is bad code
Thu. Oct. 19th, 2006 7:06 PM    Beginner bugmenot

Voting