Question

function Todo(id, task, who, dueDate) {
    this.id = id;
    this.task = task;
    this.who = who;
    this.dueDate = dueDate;
    this.done = false;
}


function updateDone(e) { 
      var spanClicked = e.target;
      var id = spanClicked.parentElement.id;
      spanClicked.innerHTML = " ✔ ";
      spanClicked.setAttribute("class", "done");
      console.log("you clicked this span" + id);


      for(var i = 0; i < todos.length; i++) {
        if (todos[i].id == id) {
            var mark = todos[i];
            mark.setAttribute("class", "done");
            console.log(mark);
            break;
            }
           } 
    }

The first part of this function updates the webpage to show that an object is "done". The second part is where I'm having problems. I'm trying to update the object as "done" inside of an array. The idea was to match the id of what the user clicks on to the id in the array and then set it as "done" by using setAttribute. However the console message that I get for console.log(mark) is mark.setAttribute is not a function. Any suggestions on how I can modify this so that I can update the object in the array as "done"?

Was it helpful?

Solution

for(var i = 0; i < todos.length; i++) {
    if (todos[i].id == id) {
        var element = document.getElementById(todos[i].id);
        element.setAttribute("class", "done");
        console.log(element);
        break;
    }
}

or if "mark" in your example is not a DOM object, then you would just set it's done property to true.

for(var i = 0; i < todos.length; i++) {
    if (todos[i].id == id) {
        todos[i].done = true;
        console.log(todos[i]);
        break;
    }
}

OTHER TIPS

Setting class with setAttribute is not a great idea.

//Works with FF and Chrome
obj.setAttribute("class", "done");

//works with IE
obj.setAttribute("className", "done");

//works with all browsers
obj.className = "done";

Hey @user2084813 I know this will seem a bit overkill but it will be useful in the long run. JQuery has functions that works cross browser(never have to check validation) that allows you to check/add/remove classes. IE usually handles removing differently.

http://api.jquery.com/hasClass/

http://api.jquery.com/addClass/

http://api.jquery.com/removeClass/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top