Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript innerHTML manipulation with "onclick" handler

Tags:

javascript

I wanna know how I can change the innerHtml to switch back and forth between two states. I have this html

 <div class="test" id="test">
    <p>this is a test</p>
</div>
<p id="js" class="test" >Change</p>

and this is the JavaScript I have

let button = document.getElementById("js");

button.onclick = function() {
document.getElementById("test").innerHTML = "test";
};

how can I change the innerHTML from "test" to "another test" and vice versa ?

like image 959
Sam Lahm Avatar asked Dec 07 '25 20:12

Sam Lahm


2 Answers

It's better not to store state in the HTML - don't test against what's currently in the HTML, keep a variable in your Javascript instead.

You should also only use let when you want to warn other programmers that you're going to reassign the variable in question - otherwise, use const.

Also, if you're changing the text of an element, assign to textContent instead - it's safer, faster, and more predictable.

const button = document.getElementById("js");
const test = document.getElementById("test");
let clicked = false;
button.onclick = function() {
  clicked = !clicked;
  if (clicked) test.textContent = 'another test';
  else test.textContent = 'test';
};
 <div class="test" id="test">
    <p>this is a test</p>
</div>
<p id="js" class="test" >Change</p>
like image 117
CertainPerformance Avatar answered Dec 10 '25 11:12

CertainPerformance


First, .innerHTML is only for when you are setting/getting a string that contains HTML. When you are not, use .textContent, which is more efficient and reduces security risks.

Then, you only need a toggling if statement, which can be done with a JavaScript ternary operator.

Also, rather than using event properties, like onclick. Use .addEventListener(), which is more robust and follows the modern standard.

// Get a reference to the <p> that is inside of the element who's id is "test"
let output = document.querySelector("#test p");

// Set up an event handler for the "Change" element
document.getElementById("js").addEventListener("click", function() {
  // Check the current textContent and set it to the other value
  output.textContent === "test" ? output.textContent = "another test" : output.textContent = "test";
});
<div class="test" id="test">
    <p>this is a test</p>
</div>
<p id="js" class="test" >Change</p>
like image 21
Scott Marcus Avatar answered Dec 10 '25 11:12

Scott Marcus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!