Link to home
Start Free TrialLog in
Avatar of phasevar
phasevar

asked on

Identify instance in Array


I have an array which is populated with references to DOM instances.

var divs = new Array();
// populate array


At a later time some DOM instances may be removed from the document tree.  When they are removed I want to remove them from the array as well.  This is going to require a loop through the array to find each DOM instance to remove.  However, how to compare for the match?  I could assign each DOM instance an ID, but I'm wondering if there is a more direct way to compare instances.

for(var x=0; x<divs.length; x++) {
    if(divs[x] = this_div) {
        // remove divs[x]
    }
}

Other than for this purpose, my DOM instances dont really need an ID.  But my attempts to compare instances otherwise has failed.  Is this my only option?
Avatar of Zvonko
Zvonko
Flag of North Macedonia image

How about this:

<html>
<head>
<script>
var divs = new Array();
function show(obj){
  msg = ""
  for(p in obj){
    msg += p+": "+obj[p]+"\n"
    if(msg.length>700){
      alert(msg)
      msg=""
    }
  }
  alert(msg)
}
</script>
</head>
<body>
<div onClick="divs['i'+this.sourceIndex]=this.innerHTML">FirstDiv</div>
<div onClick="divs['i'+this.sourceIndex]=this.innerHTML">SecondDiv</div>
<a href="javascript:for(d in divs)alert(divs[d])">Show divs[]</a>
</body>
</html>

Avatar of phasevar
phasevar

ASKER

The sourceIndex property will not work because it is IE specific.  I need something that works with Mozilla as well as IE.  I also checked out the uniqueID property and it's the same story there.

So back to square one.  How do I compare two object instance references to see if they point to the same object.
You could also invent a new attribute for your objects, like an unique id used only for the array index. That could be some counter  or something else what is unique.
The adavantage of the associative array is that you can access the Array slot directly if you have that string identifying your object. And the identifier can be stored inside the object as long as the object is not deleted.
Oh, and with that unique object attribute you need not to compare the array elements: you jump derectly to the one array elemnt referenced by the object identification string.
You have to take care that those identification strings are not all digit chars.
ASKER CERTIFIED SOLUTION
Avatar of Zvonko
Zvonko
Flag of North Macedonia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks!  I guess I'll have to go with assigning each instance an id.