0

Dear StackOverflow community,

I am new to jQuery and Javascript, and was wondering what the main differences between these two functions are:

document.getElementById('id').innerHTML      =variable;

and

jQuery('#id').val(variable);

From my understanding, they are two different coding techniques, but when would I use one over the other? and why?

NoahMCM
  • 601
  • 1
  • 5
  • 8

1 Answers1

3

The two above examples are slightly different, but not in the way you're expecting.

  • innerHTML and .val() are not equivalent methods.

  • jQuery will try to use querySelector / querySelectorAll where appropriate when using the DOM selection jQuery("SELECTOR"). These are native methods, so look into them.

  • .val(variable) will set the value of the node found by jQuery("SELECTOR") to variable

  • innerHTML = variable will set the the HTML content of document.getElementById('id') to whatever variable is.

.val() - Set the value of each element in the set of matched elements.

innerHTML - innerHTML sets or gets the HTML syntax describing the element's descendants.

Chase
  • 29,019
  • 1
  • 49
  • 48