0

I'am trying to dynamically add an attribute to my HTML element. After the operation, the attribute is successfully added, but I can't see it in my HTML via the browser console. What's odd is this case, it's the fact that I can display the value of the attribute using console.log.

let xhr = new XMLHttpRequest();
xhr.responseType = 'json';
xhr.onreadystatechange = function() {
    if (xhr.readyState === XMLHttpRequest.DONE) {
        let result = xhr.response;
        appendFileIdsToExtraFields(result.ids,source)
    }
};

The appendFileIdsToExtraFields it's the method in charge of adding the new attribute.

$(ids).each(function (key, value) {
    $('#file-'+(key+1)+'-description').attr('data-id',value);
    console.log($('#file-'+(key+1)+'-description').data('id'));
});

And here's the value displayed in the console

enter image description here

But not in the element

enter image description here

KubiRoazhon
  • 1,759
  • 3
  • 22
  • 48
  • Possible duplicate of [jQuery Data vs Attr?](https://stackoverflow.com/questions/7261619/jquery-data-vs-attr) see the jQuery docs, using `data`, you store in javascript memory, not directly in the attribute. By the way, never mix `data('prop')` with `attr('data-prop')` or it will lead to unexpected behaviour – Kaddath Jan 15 '19 at 12:55
  • unfortunately, I used them both @Kaddath. But the result is the same. – KubiRoazhon Jan 15 '19 at 12:57
  • 2
    I know the feel, i had to harmonize all of them in our project's code.. I recommend sticking to `data` only, as `attr` will lead to unnecessary access to the DOM. Note that when the attribute exists in the DOM, by using `data` you will get this value only the first time, if you use a second time, you'll have the value that is stored in JS – Kaddath Jan 15 '19 at 13:05
  • The attribute does not exist. I've tried to create one and replace the value already defined using my method. But the same result, nothing happened. – KubiRoazhon Jan 15 '19 at 13:16
  • we dont see the whole HTML element in your picture, using `attr`, the attribute should be there in the DOM, maybe is it hidden behind a `...` because there are many? By the way, do you really need it to be visible in the DOM? – Kaddath Jan 15 '19 at 13:35
  • @Kaddath Not necessary. I put just the first part of the html element, but I am sure. It doesn't exsists. – KubiRoazhon Jan 15 '19 at 13:41
  • can you reproduce in a snippet here? because in my tests it works.. – Kaddath Jan 15 '19 at 13:53

0 Answers0