Search code examples
javascriptdomhtml-inputgetattribute

Value of HTML input range, getattribute vs value


I have created HTML INPUT element with type="RANGE" and with id="slider". Why cannot I access its value using getAttribute("value") method? Debugger shows that there is an attribute named "value" with some value which is not equal to the value of the element. Should not the value of range element be its attribute?

var sliderValue1=document.getElementById("slider").getAttribute("value");
var sliderValue2= document.getElementById("slider").value;

Solution

  • Why cannot I access its value using getAttribute("value") method?

    you can't do that because, .getAttribute("value") return the value of the element write into the html (if you don't change that, the default value).

    Example:

    with: <input type="range" id="slider" value="500">

    document.getElementById("slider").getAttribute("value"); return 500 also if you use input to change range.

    Debugger shows that there is an attribute named "value" with some value which is not equal to the value of the element.

    It's true, and right. If you set a default value it never change (is useful to reset the input).

    Should not the value of range element be its attribute?

    No, the current value of the element is stored outside the html, so to access to the current vale you must use: document.getElementById("slider").value;, but it's the same with all type of input not only on range.

    $(function(){
        $("input[name=foo]").on("change",function(){
            var val = $(this).val();
            var attr = $(this).attr("value");
            var prop = $(this).prop("value");
            console.log(" --- JQUERY TEST JS ----");
            console.log("Current value: (using .val)",val);
            console.log("Initial value: (using .attr)",attr);
            console.log("Current value: (using .prop)",prop);
        });
    });
    
    //NATIVE JS
    function originalJS(){
        console.log(" --- ORIGINAL JS ----");
        console.log("Current value: (using .value)",this.value);
        console.log("Initial value: (using .attr)",this.getAttribute("value"));
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
    <input type="range" onChange="originalJS.call(this)" name="foo" value="500"/>
    <p>RUN AND WATCH CONSOLE :) ... watch value="500" (but range is 0-100)</p>
    
    <input type="text" onChange="originalJS.call(this)" name="foo" value="500"/>