Andrew Steier
Andrew Steier

Reputation: 133

Dynamically created list items draggable JavaScript

I am dynamically populating a list of senators, separated by political affiliation. That part works. I need to make each list item draggable. I can't get that to work.

I tried this:

document.getElementById(name).setAttribute('draggable');

in my list population loop, but I really don't know if that's the right way.

senatorList.forEach(({name, party}) => {
    let itemEl = document.createElement('li');
    itemEl.textContent = name;
    let listId = party === 'Democrat' ? '#democrats' : '#republicans';
    let listEl = document.querySelector(listId);
    document.getElementById(name).setAttribute('draggable');
    listEl.appendChild(itemEl);
  });

Upvotes: 0

Views: 62

Answers (1)

GalAbra
GalAbra

Reputation: 5148

Your code contains a couple of errors:

  1. setAttribute requires two arguments: attribute and value.
  2. You called document.getElementById(name) before adding itemEl to the document.

If I understood your intentions correctly, the code should look similar to this:

const senatorList = [{
    name: 'senator1',
    party: 'Democrat'
  },
  {
    name: 'senator2',
    party: 'Democrat'
  },
  {
    name: 'senator3',
    party: 'Republican'
  },
];

senatorList.forEach(({
  name,
  party
}) => {
  let itemEl = document.createElement('li');
  itemEl.textContent = name;
  let listId = party === 'Democrat' ? '#democrats' : '#republicans';
  let listEl = document.querySelector(listId);
  itemEl.setAttribute('draggable', 'true');
  listEl.appendChild(itemEl);
});
<div id="democrats"></div>
<div id="republicans"></div>

Upvotes: 1

Related Questions