what is the difference between using $ (). val () and document.getElementById (). value; in javascript

3

Well I'm a bit confused about how to get the value of the fields in Javascript, I've seen that many times you get using the code:

document.getElementById("elemento").value;

and others using the code:

$(elemento).val()

What is the difference?

    
asked by condor12 13.07.2017 в 21:38
source

5 answers

3

They are two ways of doing the same thing.

$ is the variable name that references the document object in jQuery, a very popular JavaScript library . The official jQuery documentation is at link

document is a variable that refers to the document object.

The object document has the purpose of handling in memory the content of the web page loaded in the browser. What governs its characteristics is known as Document Object Model, in English Document Object Model or DOM. It does not form part of the ECMAScript specification which is the standard for specifying how JavaScript engines should handle the scripts made with this language, but it has its own standard published by W3C.

The web address of the ECMAScript is link

The web address on the DOM is link

jQuery arose when JavaScript lacked simple ways to perform operations with the DOM however over the years it has improved as well as jQuery has done, however, other libraries have emerged and frameworks that offer similar things. The frameworks are tools that can help a programmer to be more efficient but like any tool, you should choose the right one for the task.

Related to Should jQuery be used in "all" HTML / CSS / JavaScript application?

    
answered by 13.07.2017 / 23:59
source
2

When you use $ you are referring to JQuery which is a javascript framework, its main use is that of selector, which is the example you give, but it has many more uses, such as animations, simpler ajax requests and much more. For more information visit the home page . When you use document.getElementById("elemento") you are using the native javascript form to reference an element by id. In JQuery it is:

var elemento = $('#id'); //referencia por id
var elemento = $('p'); //referencia por tipo, en este caso todas las etiquetas p
var elemento = $('.clase'); //referencia por clase, todas las etiquetas 
// que tengan la clase 'clase' estarán contenidas dentro de la variable elemento
    
answered by 13.07.2017 в 21:41
2

They do the same, as Reinier says $ refers to Jquery while GetElementById is the native Javascript method.

I remind you that Jquery is written in Javascript so, bring the value of the two forms is valid.

function myfunction(){
  var valor = document.getElementById('box').value;
  alert(valor);
}


$(function(){

  $(document).on('click','#btn',function(){
  var valor = $('#box').val();
  alert(valor);
  });
});
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <input type="text" id="box" value="prueba">
  <input type="button" id="btn" value="Prueba con Jquery">
  <input type="button" onclick="myfunction()" value="Prueba con Javascript">
    
answered by 13.07.2017 в 23:29
2

The difference is that the code without jQuery is of a single line, whereas with jQuery they are many lines, and it is an elaborate code that tries to work in all the browsers.

Without jQuery :

document.getElementById().value;

To get the code of the function val in jQuery , do the following, using the uncompressed version of jQuery called slim , in your downloads section :

console.log($().val+"")
<script src="https://code.jquery.com/jquery-3.2.1.slim.js"></script>

The answer I got was the following:

function val( value ) {
    var hooks, ret, isFunction,
        elem = this[ 0 ];

    if ( !arguments.length ) {
        if ( elem ) {
            hooks = jQuery.valHooks[ elem.type ] ||
                jQuery.valHooks[ elem.nodeName.toLowerCase() ];

            if ( hooks &&
                "get" in hooks &&
                ( ret = hooks.get( elem, "value" ) ) !== undefined
            ) {
                return ret;
            }

            ret = elem.value;

            // Handle most common string cases
            if ( typeof ret === "string" ) {
                return ret.replace( rreturn, "" );
            }

            // Handle cases where value is null/undef or number
            return ret == null ? "" : ret;
        }

        return;
    }

    isFunction = jQuery.isFunction( value );

    return this.each( function( i ) {
        var val;

        if ( this.nodeType !== 1 ) {
            return;
        }

        if ( isFunction ) {
            val = value.call( this, i, jQuery( this ).val() );
        } else {
            val = value;
        }

        // Treat null/undefined as ""; convert numbers to string
        if ( val == null ) {
            val = "";

        } else if ( typeof val === "number" ) {
            val += "";

        } else if ( Array.isArray( val ) ) {
            val = jQuery.map( val, function( value ) {
                return value == null ? "" : value + "";
            } );
        }

        hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];

        // If set returns undefined, fall back to normal setting
        if ( !hooks || !( "set" in hooks ) || hooks.set( this, val, "value" ) === undefined ) {
            this.value = val;
        }
    } );
}
    
answered by 14.07.2017 в 05:15
0

As everyone has expressed, .val() and .value is the same but I wanted to add something.

The reason why .val() is used on .value is to make sure it works on all browsers. For example .innerHtml did not work the same in all browsers but jquery we solve it with .html() , doing all the dirty work of making it work according to the browser and thus giving a single method for all browsers (desktop and smartphone). It gives us an easy API to manipulate the DOM.

    
answered by 14.07.2017 в 04:23