简体   繁体   中英

Dynamically Change ID of an HTML Element with Javascript

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.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM