Exploring innerHTML in JavaScript for event listening

Two code snippets were tested, one worked as expected while the other didn't produce the desired result. The goal was to display a different text every time a user clicked on a button. However, the unsuccessful code always displayed err, with no change in text or console output except for an increasing number next to err.

function func1() {
    let x = document.getElementById("test1").innerHTML;
    if (x==="") {
        x = "First click";
        console.log("err");
    } else if (x==="First click") {
        x = "Second click";
        console.log("err2");
    } else {
        x = "Third click";
    }
}

document.getElementById("click").addEventListener("click", func1);

The second code snippet below functioned perfectly:

function func1() {
  let x = document.getElementById("test1");
  if (x.innerHTML === "") {
      x.innerHTML = "First click";
      console.log("err");
  } else if (x.innerHTML === "First click") {
      x.innerHTML = "Second click";
      console.log("err2");
  } else {
      x.innerHTML = "Third click";
  }
}

document.getElementById("click").addEventListener("click", func1);

Answer №1

Changing the value of a variable typically does not have any consequences (in most cases) - updating someVar = newValue will only impact other sections of the code that reference someVar at a later point.

For example, when you execute

let x = document.getElementById("test1").innerHTML;

you are accessing the HTML string from the element using the .innerHTML getter and storing it in the x variable. Modifying the content of the x variable does not alter the actual element. To modify the element itself, you need to update the .innerHTML property, as demonstrated by

x.innerHTML = "Second click";

which effectively changes the content.

Answer №2

If you are looking to utilize the x = syntax for changing the content of an element, one way to achieve this is by creating a property on the window object to handle the value forwarding.

Object.defineProperty(window, 'x', { get: () => document.getElementById("test1").innerText, set: (val) => document.getElementById("test1").innerText = val });
x // retrieves text value
x = 'asdf' // sets it to 'asdf'

However, this method may be considered excessive and unnecessary just to avoid using .innerText. It is advised to resort to a simpler and more secure approach like defining a function.

A cleaner alternative would involve creating a function.

function x(v) {
  if (v) document.getElementById("test1").innerText = v;
  return document.getElementById("test1").innerText;
}
x() // retrieves text value
x('asdf') // sets it to 'asdf'

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to tally a score after analyzing two spans in Javascript?

I have 3 spans where 2 contain an alphabet each. The third span is left blank for the result of comparing the first 2 spans. I need to display the result in the last span, showing a value of 1 if the two spans contain the same alphabet. Can anyone sugges ...

What is the best way to retrieve data from an Express endpoint within a React component?

I am working on integrating a React component with an Express endpoint that returns the string "sample data". The goal is to call this endpoint from my React app, store the text in state, and then display it on the screen. Here is my component: class App ...

Send the JSON output of a MySQL query as an argument to my EJS template in a Node.js/Express application

I've been using res.json(rows) to display my users on the screen, but now I want to pass the object obtained from the query to an ejs file for display. However, when I try to do this as shown in my code below, the passed object becomes a string and I& ...

Arranging asynchronous functions using async/await in Node.js/JavaScript

When it comes to organizing my code in js/nodejs, I frequently rely on this pattern. (async function(){ let resultOne = await functionOne(); let resultTwo = await functionTwo(); return { resultOne: resultOne, resultTwo: resul ...

Issue with Axios fetching data with parameter in Next.js not resolving

While working with Next.js, I encountered an issue where the input text value (email) is successfully displayed in the console, but when trying to use this value as a parameter, "{emails}" is being saved in the database instead of the dynamic email value. ...

"Change the value of a style setting in React to 'unset

One of the components has CSS properties such as `right` and `bottom` that are set with a classname. I tried to override these values using the `style` prop but have only been successful in setting numerical values like `10px` or `0px`, not `unset`. Wha ...

Tips for automatically refreshing a page after submitting a form

I have a template with two components - a filter and a request to the API. I am wondering if it's possible to update the values of the request component after submitting the filter. On the main page, the request component has default values. When a u ...

The Query.formatError message indicates that there is an issue with the 'users.email' column in the where clause of the database query

I'm having some trouble with a piece of code. Here's my signup function : exports.signup = (req, res) => { // Adding User to Database console.log("Processing func -> SignUp"); User.create({ name: req.body.name, username: req.body. ...

Whenever my NodeJs encounters an unhandledPromise, it throws an error

https://i.sstatic.net/w6sa9.png exports.createNewTour = async (request, response) => { try { const newlyCreatedTour = await Tour.create(request.body); res.status(201).json({ statusCode: "success", details: { tours ...

Antialiasing in Three.js is failing to work properly on Google Chrome

When using Chrome v31, I've noticed that antialiasing doesn't seem to be working properly. There are no errors in either browser. Here is the possibly relevant code: var renderer = new THREE.WebGLRenderer( { antialias: true } ); The rendering ...

Is there a way to get an iframe to mimic the behavior of other media elements within a horizontal scrolling container?

Take a look at this code snippet: $(document).ready(function() { $('.scrollable-area').on('wheel', function(e) { var scrollLeft = $(this).scrollLeft(); var width = $(this).get(0).scrollWidth - $(this).width(); var delta ...

Error: The function cannot be performed on _nextProps.children

I'm having trouble implementing react context with nextJS and I keep encountering this error: Server Error TypeError: _nextProps.children is not a function This is my code for _App.js: import Head from "next/head"; import Router from &q ...

The ESLint tool seems to be struggling to detect the package named "@typescript-eslint/eslint-plugin"

Struggling with getting ESLint to function properly on a new Angular project in VS Code. The error message I keep encountering is about failing to load "@typescript-eslint/eslint-plugin". After spending the past 3 hours troubleshooting, I have searched hig ...

Tips for storing form data in MongoDB

I'm currently working on a form and I need help extracting text from the form in order to save it into MongoDB. Here is an excerpt from my tweets.ejs file: <form method="post" action="/tweets"> <input type="text" id="txt" name="text"/> & ...

Utilizing the setNetWorkConditions function in webdriverjs for Chrome

Is there a way to properly utilize the webdriverjs setNetworkConditions() method as outlined in the official documentation? This is what my code looks like: const chromeCapabilities = webdriver.Capabilities.chrome() const chromeOptions = { ...

What is the process for making changes to a document in Mongoose?

My goal is to allow users to update existing mongoose documents using a form with method-override package. Despite trying various solutions found on Stackoverflow, I have not been able to resolve my issue. The desired functionality is for the user to view ...

Guide to inspecting file contents with Node.js

I am working on viewing the content of a file that is posted from the client using the fs module. However, with the code below, the contents are coming up as undefined. Can anyone help me identify what is missing in the code? To ensure I am receiving the ...

Position the spinner in the center of the user's screen

I created my own spinner: '''' #spinner-bg-loading{ position: absolute; left: 50%; top: 25%; width: 80px; height: 80px; margin: -75px 0 0 -75px; border: 16px solid #FFFFFF; border-radius: 50%; border-top: 16px solid #1 ...

How can I choose multiple criteria by utilizing the indexOf('EXAMPLE.com') method? Is there a way to add additional examples for selection?

I'm currently working on extracting specific usernames from a training portal: Up to this point, I've come up with some code that's able to select all emails containing EXAMPLE.com (as shown below) Is there anyone who could modify this cod ...

The invocation of res.json() results in the generation of CastError

An issue occurs with CastError when using res.json() with an argument: CastError: Failed to cast value "undefined" to ObjectId for the "_id" field in the "Post" model Interestingly, using just res.status(), res.sendStatus(), or res.json() without argument ...