1

I've been working on a simple object with methods to set data to DOM and to get data from DOM based on the name attribute, however, when try to set the data to an element, I don't get any error but no data is assigned to the element either. What am I doing wrong?

var $ = {
  getData: function(CLASS) {
    var a = document.getElementsByClassName(CLASS),
      b = document.getElementsByClassName(CLASS).length,
      c = {},
      d = 0;
    for (d = 0; d < b; d++) {
      c[a[d].getAttribute('name')] = a[d].getAttribute('value');
    }
    return c;
  },
  setData: function(CLASS, DATA) {
    var a = document.getElementsByClassName(CLASS),
      b = document.getElementsByClassName(CLASS).length,
      c = DATA,
      d = 0;
    for (d = 0; d < b; d++) {
      console.log(c[a[d].getAttribute('name')]);
      a[d].value = c[a[d].getAttribute('name')];
    }
    return c;
  }
};
var c = {
  "roger0": "derp",
  "roger1": "derp",
  "roger2": "derp",
  "roger3": "derp",
  "roger4": "derp"
};

$.setData('item', c);

console.log($.getData('item'));
<!DOCTYPE html>
<html>

<head>
  <title>Form</title>
</head>

<body>
  <div class="item" name="roger0" value="">0</div>
  <div class="item" name="roger1" value="">1</div>
  <div class="item" name="roger2" value="">2</div>
  <div class="item" name="roger3" value="">3</div>
  <div class="item" name="roger4" value="">4</div>
</body>

</html>
Kyle
  • 1,568
  • 2
  • 20
  • 46
  • Just a note: Descriptive variable names are really helpful when debugging. [This code does the exact same thing but with better variable names.](https://jsfiddle.net/b0ku7gh9/) Your actual problem stems from how you're getting the elements value. – Mike Cluck Apr 11 '16 at 19:10
  • Possible duplicate of [JavaScript Element.value vs Element.getAttribute("value")](http://stackoverflow.com/questions/17494432/javascript-element-value-vs-element-getattributevalue) – Mike Cluck Apr 11 '16 at 19:11

1 Answers1

1

You need to change your setData function to use the getAttribute method by editing your current function. The line below needs to be used to set the value.

a[d].setAttribute("value",c[a[d].getAttribute('name')]);

You can find further information on setAttribute() here.

setData: function(CLASS, DATA) {
        var a = document.getElementsByClassName(CLASS),
        b = document.getElementsByClassName(CLASS).length,
        c = DATA,
        d = 0;
        for (d = 0; d < b; d++) {
          console.log(c[a[d].getAttribute('name')]);
          console.log(a[d])
          a[d].setAttribute("value",c[a[d].getAttribute('name')]);
        }
        return c;
}
Paul Fitzgerald
  • 11,770
  • 4
  • 42
  • 54