0

I found a strange effect, that i can not understand. You need console @ jsfiddle to see some text

First test this (using class): https://jsfiddle.net/ojg1Lzrk/1/ set/get with element.value or attribute.nodeValue is without difference.

<input id="i" value="" class="A">

document.addEventListener('DOMContentLoaded', function(event) {
    //1) OK - should display A in console
    console.log('1)should be A:', i.className)

  //2) OK - input field should have B class
    i.className = 'B'

    //3) OK - should display B in console
    console.log('3)should be B:', i.attributes.class.nodeValue)

  //4) OK - input field should have C class
    i.attributes.value.nodeValue = 'C'
})

Next test (using value): https://jsfiddle.net/6ya98njL/2/ Now it is not synchron element.value have 'current' value and attribute.nodeValue is 'frozen' and the connection is lost

<input id="i" value="A" oninput="inp()">

document.addEventListener('DOMContentLoaded', function(event) {
    //1) OK - should display A in console
    console.log('1)should be A:', i.value)

  //2) OK - input field should be B
    i.value = 'B'

    //3) !!! - should display B in console
    console.log('3)should be B:', i.attributes.value.nodeValue)

  //4) !!! - input field should be C
    i.attributes.value.nodeValue = 'C'
})

function inp() {
    //5) !!! - different values
    console.log('5)inp start', i.value, i.attributes.value.nodeValue)

  //6) !!! no change to input field:
  i.attributes.value.nodeValue = 'Z'

    //7) !!! - different values
    console.log('7)inp end', i.value, i.attributes.value.nodeValue)
}

I found out that element.value and attribute.nodeValue is in sync, so long you not set element.value or enter a value. After that it is lost. But changing with attribute.nodeValue before is without problems.

Why is here such difference between class and value ? Even if i change class in browser/inspector, it is in sync and work always.

I found this answer about value: Difference between Element.value and Element.getAttribute("value")

So the Question is: WHY ???!!!

john49384
  • 1
  • 1
  • The answer you found is just right. Some properties of the elements are synced with attributes of the DOM (such as `class` and `.className` or `value` and `.defaultValue`), but not all of them are. A `.class` property doesn't exist at all, and `.value` is something different (although it is initialised from the `.defaultValue`) – Bergi May 05 '20 at 19:01
  • In every instance of chaining these properties `attributes.value.nodeValue` You have a problem. Try one or the other: `attributes[0].value` or `attributes[0].nodeValue`. `node.attributes` is a collection of `node`'s attributes (ex. `node.attributes[0].name`, `node.attributes[0].value` is `'class'` `'A'`) – zer00ne May 05 '20 at 19:13
  • attributes.value.nodeValue and attributes[1].nodeValue was the same for me. Here was no difference. – john49384 May 05 '20 at 19:22

0 Answers0