简体   繁体   中英

Why does this line Javascript work, but the other doesn't?

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?

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');

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');

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");

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

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";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM