Suliman Sharif
Suliman Sharif

Reputation: 607

Loop only appending to one element rather than multiple

so I can't seem to figure this one out exactly. I want to append buttons to every container that doesn't have a null id. So in the list of contents there are two items and I would like to append buttons. The problem is that it only appends to the one, the last item in the list. So my question is to why? and how to fix it.

Example Data Set

Contents

0:{item_uuid: null, label: "11"}
1:{item_uuid: "49b661aa-222b-4c3c-a3cc-92db229c500e", label: "24"}
2:{item_uuid: null, label: "25"}
3:{item_uuid: null, label: "31"}
4:{item_uuid: "49b661aa-222b-4c3c-a3cc-92db229c500e", label: "43"}
5:{item_uuid: null, label: "44"}

The Code

 for (var i = 0; i < contents.length; i++) {
      if (contents[i].item_uuid !== null) {
           $('#' + contents[i].label).append(button);
           button.setAttribute("class", "button");
      }
    }

Upvotes: 0

Views: 302

Answers (2)

prabushitha
prabushitha

Reputation: 1483

May be create the button object inside the for loop. otherwise it uses the same button instance and will append only to the last one.

for (var i = 0; i < contents.length; i++) {
      if (contents[i].item_uuid !== null) {
           var button = createElement(....); //create it here
           $('#' + contents[i].label).append(button);
           button.setAttribute("class", "button");
      }
    }

Upvotes: 1

bassxzero
bassxzero

Reputation: 5041

Your code works, but I had some strange results when trying to append the same button twice, that's why i create it in the loop. You may want to make sure you're not appended the same button to multiple containers.

E.G

 for (var i = 0; i < contents.length; i++) {
      if (contents[i].item_uuid !== null) {
        var button = $('<button>blah</button>');
           $('#' + contents[i].label).append(button);
           //button.setAttribute("class", "button");
      }
    }

Upvotes: 1

Related Questions