2

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?

3 Answers 3

10

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.

Sign up to request clarification or add additional context in comments.

3 Comments

you can also get the html element itself with [0]. so `$("#testScore")[0].innerHTML = '...';
You'll need to put bucket.score out of the string (move the single quote ' to the left) to have it evaluated.
The [0] part could be written as $('#testScore').get(0), too.
2
function updateScore() {
    alert("Test score is: " + bucket.score);
    $("#testScore").text('Current score is: ' + bucket.score);
}

Comments

0

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.

5 Comments

Nope, didn't work. You can see my page and view the source if you need to here: elliot.bonblogs.com/quiz/#quiz
It's not innerHTML(), it's html().
A JavaScript limitation? This does not make sense to me.
@elusive, its a JavaScript limitation because they couldn't override the meaning of obj.innerHTML = X to do something special.
@Winston Ewert: I do not think that they did it like they did because of non-existing magic properties in JavaScript. .html() simply fits much better in the jQuery schema. It is chainable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.