0

So this is roughly the first HTML/CSS/JavaScript thing I've done.

function update_text(element) {
  element.innerHtml = "Hello Other!";
  console.log("JS Ran");
}
<p onclick="update_text(this)">Hello World!</p>

Based on what I read online, when the text "Hello World!" is clicked, it should change to "Hello Other!", but it does not. The console.log statement shows up in the console so I know it is running.

Optimally, this would work several times. For example, maybe the js function sets the text to "It is <current time>".

isherwood
  • 58,414
  • 16
  • 114
  • 157
T. Smith
  • 124
  • 8
  • 5
    There is no `innerHtml` property. It’s [`innerHTML`](//developer.mozilla.org/docs/Web/API/Element/innerHTML). – Sebastian Simon Sep 08 '21 at 20:27
  • 2
    Inline event handlers like `onclick` are [not recommended](/q/11737873/4642212). They are an [obsolete, hard-to-maintain and unintuitive](/a/43459991/4642212) way of registering events. Always [use `addEventListener`](//developer.mozilla.org/docs/Learn/JavaScript/Building_blocks/Events#inline_event_handlers_%E2%80%94_dont_use_these) instead. – Sebastian Simon Sep 08 '21 at 20:28

3 Answers3

1

Change innerHTML to innerText.

It is best practise to do this externally in your JS file, rather than inline :)

Edit: I just noticed you used innerHtml and not innerHTML, innerHtml isnt a thing! :D

HollosJ
  • 11
  • 4
  • A classic mistake on my part. Do you mind expanding on the best practice? Edit: Nevermind. I figured out what you meant based on Sebastian Simon's comment. – T. Smith Sep 08 '21 at 20:52
  • No worries everyone makes the same mistake in the beginning. https://stackoverflow.com/questions/43459890/javascript-function-doesnt-work-when-link-is-clicked/43459991#43459991 Someone else said the same thing and linked this, it explains it pretty well :) – HollosJ Sep 08 '21 at 20:55
1

You need to change InnerHtml to InnerHTML

function update_text(element)
{
    element.innerHTML = "Hello Other!";
    console.log("JS Ran");
}
<head>
    <title>My First Webpage</title>
    <meta charset="UTF-8">
    <link rel='stylesheet' href='../css/style.css'>
    <script src='../javascript/main.js'></script>
</head>

<body>
    <p onclick="update_text(this)">Hello World!</p>
</body>
Arianne
  • 507
  • 2
  • 7
1

There is no property in HTML element object as innerHtml, it's actually innerHTML. But you can also use innerText. You can check in this demo

JAVASCRIPT

function update_text(element)
{
    element.innerHTML = "Hello Other!";
    
    // You can also use innerText
    // element.innerText = "Hello Other!";

    console.log("JS Ran");
}
iftikharyk
  • 870
  • 5
  • 10