1

Alright. I have created a custom object that I am using to build a list of things. One of the functions for this custom object involves adding the object to a list. In this list, there is a value I assign to each different element that keeps track of how many of that item have been added to the list. Such as:

(3) Object#1
(2) Object#2

3 and 2 of course being the 'count' value of that object. My problem is that I am creating the list dynamically by calling:

function Thing(count, value)
{
    this.count=count;
    this.value=value;
}

Thing.prototype.addToList = function()
{
if (this.count == 0)
{
    this.count++;

    var list = document.getElementById("blah");
    var li = document.createElement("li");
    var interior = "<span id='counter'>("+this.count+")</span>";
    li.innerHTML = interior;
    list.appendChild(li);
}
else
{
    this.count++;
    var countInc = document.getElementById("counter");
    countInc.innerHTML = "("+this.count+")";
}
}

This works fine, but if I am to add multiple Objects with separate count values, there is no way to distinguish between them, and as a result, the first 'counter' span in the list is altered with the the count value of the most recently added object. All other count values remain the same (1). I have tried:

var interior = "<span id='counter"+this.value+"'>("+this.count+")</span>";

To try and create a unique id each time, but this isn't working. Basically, I am wondering how I can create new ID values each time I instantiate a new Object.

3
  • Are you using the new keyword? That should ensure that you have unique objects. Commented Jul 18, 2012 at 19:20
  • @arxanas yes, I instantiate them via: var object1 = new Thing (0, "blah"); Commented Jul 18, 2012 at 19:23
  • the problem is that the id for counter span is the same for all different instances of the object, just need to know the correct way to change the id name for each different object so no two objects have the same id associated with their count value. Commented Jul 18, 2012 at 19:28

1 Answer 1

1

try this

var list = document.getElementById("blah");
var li = document.createElement("li");
var interior = "<span id='counter-"+this.count+"'>("+this.count+")</span>";
li.innerHTML = interior;
Sign up to request clarification or add additional context in comments.

4 Comments

no, i want to change, the id of the span so its different for each instance of the Thing object.
yeah, nice, what the hell is the issue with what i was doing? All it took was a dash?
you were doing this.value and there is nothing like this.value
I literally did exactly what you have above except without the dash after counter, didn't work. Then I add the dash after counter and it works?? quirky

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.