Elliot Bonneville
Elliot Bonneville

Reputation: 53311

Why doesn't innerHTML work on jQuery collections?

This function uses jQuery to modify the contents of a DOM element. What am I doing wrong?

function updateScore(score) {
  console.log("Test score is: " + score);
  $("#testScore").innerHTML = 'Current score is:' + score;
}

updateScore(1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>

<p id="testScore">

The log message shows up, but nothing else does. I have a <p> with the id testScore, but it doesn't change when I run the function. Why?

Upvotes: 2

Views: 1256

Answers (3)

Konerak
Konerak

Reputation: 39763

Try .html() on a jQuery object. innerHTML is for DOM-Elements.

$("#testScore").html('Current score is: '+ bucket.score);

If, for some reason, you really want to use innerHTML, you can convert the jQuery Object back to its DOM variant, for example using [0] or .get(0). Call like this, then:

$("#testScore")[0].innerHTML ='Current score is: '+ bucket.score

But I don't see why you would want to do that - since you're already writing in jQuery, there's no need to fallback to DOM methods that have a perfectly fine jQuery equivalent.

Upvotes: 10

aefxx
aefxx

Reputation: 25249

function updateScore() {
    alert("Test score is: " + bucket.score);
    $("#testScore").text('Current score is: ' + bucket.score);
}

Upvotes: 2

Winston Ewert
Winston Ewert

Reputation: 45039

try

$("#testScore").innerHTML('Current score is: + bucket.score');

The jQuery objects do not support assignment to the attributes. (Its a Javascript limitation) You have to call the function with a parameter to set something.

Upvotes: 0

Related Questions