Search code examples
javascripthtmldom-events

HTML DOM Object / Property as a variable problem


Trying to create a selector/variables in javascript but I can't get it to work.

This one doesn't work.

var checkbox = document.getElementById(ID).checked;
checkbox = true;

This one works

var checkbox = document.getElementById(ID);
checkbox.checked = true;

What is the difference?

Which part of the javascript rules have I managed to avoid by accident ?

EDIT

thanks, I understand now that I am storing the value not a reference in the variable. is it possible to save a direct reference to checked or is it impossible?


Solution

  • The difference is very simple. lets understand by a simple example.

    var checkbox = document.getElementById('vehicle1').checked;
    checkbox = true;
    

    Above you simply extracted the value of checkbox and later making change in the variable directly which has no relation directly with the DOM element by id vehicle1

    and In the below example you simply tried to change the checked value of checkbox directly.

    var checkbox1 = document.getElementById('vehicle1');
    checkbox1.checked = true;
    

    The proper reference example will be something like this

    var checkbox1 = document.getElementById('vehicle1');
    var dummyCheckbox = checkbox1
    dummyCheckbox.checked = true;
    

    you can go through this article to get the idea https://www.freecodecamp.org/news/javascript-assigning-values-vs-assigning-references/#:~:text=When%20we%20assign%20a%20reference,variable%20affect%20the%20original%20value.&text=In%20the%20example%20above%2C%20the%20variable%20array2%20is%20assigned%20a,to%20the%20original%20array%20array1%20.