0

So I'm trying to update the contents of a div #letters. I tried assigning the element to a variable and updating its content using innerHTML, but it doesn't work.

  var $characterArray = $('#letters'); // The letters div
  $characterArray.innerHTML = "whatever";

While this works:

  document.getElementById("letters").innerHTML = "whatever";

Can you please tell me why?

StudioTime
  • 22,603
  • 38
  • 120
  • 207
Gannicus
  • 530
  • 1
  • 7
  • 26

4 Answers4

5

Because you're muddling jQuery with native JS. The jQuery object has no such property innerHTML - that is a native property.

The equivalent in jQuery is the method html()

$('something').html('my html');
Mitya
  • 33,629
  • 9
  • 60
  • 107
2

The first code snippet uses the jQuery library (not vanilla JS) which has different method names for setting the inner HTML content of an element. Correct usage of jQuery is:

var $characterArray = $('#letters'); // The letters div
$characterArray.html('whatever');
adaam
  • 3,700
  • 7
  • 27
  • 51
2

The first line is not vanilla Javascript. It requires the JavaScript Framework called jQuery.

If you like to rely on jQuery and you included it in your page then you can use html():

$("#letters").html("whatever");

P.S. I assumed that you did not know about jQuery because the jQuery-tag was added later through @DarrenSweeney.

Community
  • 1
  • 1
mgutt
  • 5,867
  • 2
  • 50
  • 77
2

If you really want to code against the native HTML element you can use indexes to get to it:

var $characterArray = $('#letters')[0]; // The letters div
$characterArray.innerHTML = "whatever";
garryp
  • 5,508
  • 1
  • 29
  • 41