JavaScript - What is the best way to remove an existing value from a DIV element?

I'm currently developing a game where two players engage in combat.

Currently, I have managed to set up the system so that the player's health points (hp) are displayed as 100. However, when an event occurs causing the player to take 10 damage, instead of updating the hp bar to reflect 90, it simply concatenates and displays 10090.

How can I modify my code so that the previous value is updated rather than being appended next to it?

function player(hp, mana, stamina){
    this.hp = hp;
    this.mana = mana;
    this.stamina = stamina; 
}

function npc(hp, mana, stamina) {
    this.hp = hp;
    this.mana = mana;
    this.stamina = stamina;
}

var alistar = new player(100, 50, 30);
var dragon = new npc(100, 50, 30);

document.getElementById("hp").innerHTML += alistar.hp;

if (0 < 1) {
    alistar.hp = alistar.hp - 10;
    document.getElementById("hp").innerHTML += alistar.hp;
}

Using the "=" sign to update the value works, but it removes any HTML content I had in place. I may consider creating a second div box for my HTML needs and keeping the value separate.

Answer №1

If you want to replace the += with a simple =, just use the = symbol instead:

The = operator will overwrite the previous value, while the += combines the + and = operators for a quicker way to achieve the same result:

For example, if you need to add a value to a variable, you can do it like this:

var x = 3,
    value = 10; /* Your value, e.g. 10 */

x = x + value; /* x now equals 13 */

HOWEVER, you could achieve the same outcome using the += operator:

var x = 3,
    value = 10; /* Your value, e.g. 10 */

x += value; /* This adds the value of x to the value of the variable 'value'. */

In both cases, the value of x would be 13.


Looking at your code...

CODE:

if (0 < 1) {
    alistar.hp = alistar.hp - 10;
    document.getElementById("hp").innerHTML = alistar.hp; 
}

Answer №2

when ( 1 > 0) {
alistar.hp = alistar.hp - 10;
document.getElementById("hp").innerHTML = alistar.hp;

}

In this context, the operator += is combining values as strings instead of adding them together. To correct this, you should use "=" to assign the hp value to the hp element, replacing the current innerHTML.

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

Step-by-step guide on removing the focusin event listener from a Bootstrap 5 modal

My current app has a legacy modal that uses a kendo dropdown list element bound to an ajax call with filtering. I'm trying to avoid rewriting this component if possible. However, there is an issue where when the modal opens and you focus on the dropdo ...

Differences in CSS text padding when rendered in Firefox compared to Chrome and other web

Seeking assistance with a site issue that has been causing frustration. I have spent the entire evening trying to solve it without success. The issue at hand involves modifying tag appearance after each article on my website. The problem arises when viewi ...

Click to position custom text on image

Is there a way to adjust the position of text on an image after it has been clicked? I have included an image below to demonstrate how I would like it to appear: https://i.stack.imgur.com/unmoD.png function revealContent(obj) { var hiddenText = obj. ...

Switching between different views in Angular UI-router by selecting one UI-view over another

On my page, I have set up 2 ui-views. The top view contains a form and some controls, while the bottom view initially displays a few tables but should change based on the user's actions in the top view. I chose to keep this initial setup within a sin ...

Display solely the content within a specific Div

Currently facing an issue that needs to be resolved. I have a number of divs, each of which reveals a Span containing some text when hovered over. I've written a jQuery script for this functionality, but it currently displays all the Span elements whe ...

A guide on implementing header and sidebar rendering post login with Vue

In my Vue.js application, I am currently rendering it using different pages. A problem I'm facing is that when I log in for the first time, it only renders the main component of the page according to vue router. I want the login function to execute an ...

Why does the script source direct me to localhost:5000?

https://i.sstatic.net/X0TKs.png Hello fellow developers! I've encountered an issue while attempting to keep my javascript file separate from my .ejs files. Despite pointing my script tag to "../client/index.js," which is the correct location of the f ...

Error: The object "request" has not been defined. This issue occurs when trying to execute an Action

$dd = "<a href='javascript:void(0);' id='requestsend$send_id' onClick='request($send_id,request_send);' class='post-add-icon inline-items'><button type='button' style='background: #ccc;' ...

Encountering CORS Issue when attempting to upload a file from an external URL using Angular

I am attempting to upload a file from an external URL, but I keep encountering a CORS error when trying to access the external URL. await fetch(url).then(function (res) { response = res; }).catch(function () { setTimeout(() => { this.toaster. ...

Creating a single row on the Wordpress options page with a colspan in the first row

On my WordPress options page, I am utilizing the Fluent Framework to create fields. This framework is quite similar to Meta Box, as both make use of the do_settings_fields function to generate code like the following: <table class="form-table"> < ...

The Evolution of Alternatives to contentEditable

Related: ContentEditable Alternative I am curious about the timeline of online WYSIWYG editors prior to the existence of contentEditable. I remember using GDocs and GMail with rich-text features that functioned similarly to contentEditable. I would appre ...

Triggering a JQuery Toggle Button

This is the code I'm currently working with: $('.access a').toggle(function() { $('link').attr('href', 'styles/accessstyles.css'); $('body').css('font-size', '16px'); }, fu ...

Disabling the NavBar occurs when aligning it to the right

When attempting to align my NavBar to the right, I noticed that using float:right caused it to shift to the right but become unresponsive. Take a look here: goo.gl/46yUrt Snippet of Code: /** * 4.2 Navigation * --------------------------------------- ...

How to center the navigation text on a WordPress website within the header.php file

Check out my website at I'm looking to center the navigation menu under the image. I've attempted multiple methods but can't seem to figure it out. Here's a snippet from the header.php file: <center><img src="http ...

Utilizing Java to Store HTML Content in MySQL

Currently, I am immersed in a project that requires storing webpages in a database. To accomplish this task, I am utilizing crawler4j for crawling, along with Proxool and MySQL Java Connector to establish connections with my database. During testing, an e ...

Resizing Wordpress images to uniform height within a Bootstrap flex-row with flex-nowrap styling

I have successfully integrated Bootstrap with a Wordpress Underscores Template. My goal is to create a horizontally scrollable container filled with images of equal height. Currently, I am facing an issue where the images within the scrollable container ...

ControlsContainer - jQuery object for Flexslider

I recently tried to implement a flexslider with controls in a separate div using the controlsContainer option provided by flexslider. The setup consists of a left column containing the slider code (".flexslider-small"), a right column with text, and the c ...

Design your own unique HTML webpage

My goal is to create a screen using divs that includes a big div which aligns with the month of October. This big div should be movable across the months, and when it stacks on a specific month, a form should be submitted. I am seeking assistance with po ...

Encounter a routing issue in Node.js/Express

I am encountering an error Cannot Get / while working on my project, and this is my current folder structure: Below is the content of my route.js file: //route.js 'use strict'; var app = require('../../config/express'); var router ...

How can we server-side render the inner contents of an iframe in ReactJS to optimize SEO?

I am currently developing an application that is capable of supporting both client-side and server-side rendering through the use of Facebook's React JS framework. One of the requirements I have is to render an iframe that contains some HTML content. ...