What is the best way to update a section of an HTML file without changing the entire "inner.html"?

I'm working on a counter that can either count backwards or in ascending order based on requirements. The counter is functioning correctly, but I want to add text to accompany each number as it counts. The issue is that the text changes every time there's a change in the countdown. How can I modify the inner HTML of only part of the content without affecting the entire display? I need the text to remain constant.

Here is the HTML and JS code:

<div class="container">
  <div class="number mt-3">100 **[I WISH TO INSERT TEXT HERE]** </div>
   
</div>

JS

const numberEl = document.querySelector('.number');
let startNumber = parseInt(numberEl.innerHTML);
const endNumber = 0;

const ticker = setInterval(() => {
  numberEl.innerHTML = startNumber--;
  if(startNumber === endNumber - 1) {
    clearInterval(ticker);
  }
}, 200);

You can also access the codepen example here: https://codepen.io/kenkozma17/pen/XWdbdrd

Answer №1

If you want to add additional text in the countdown display, you can use the += operator to append HTML and insert a line break by using <br>.

numberEl.innerHTML += "<br>" + startNumber--;

To customize the appearance of the countdown number, enclose it within a span tag inside the parent div, allowing for easy modification of other text elements.

<div class="number mt-3"><span>100</span> **[INSERT TEXT HERE]** </div>
<script>
numberEl.querySelector('span').innerHTML  = startNumber--;
<script>

Answer №2

There's another option if you want to achieve a similar result:

<div class="container">
  <h2>Watch as this number goes up from 100 to 200</h2>
  <p><span class="number mt-3">100</span>Some additional information here</p>
</div>

Answer №3

If you want to give this a shot, follow these steps:

const numElement = document.querySelector('.number');
let initialNum = parseInt(numElement.innerHTML);
let additionalText =  document.querySelector('.number span').innerText;
const finalNum = 300;

const counter = setInterval(() => {
  numElement.innerHTML = (initialNum++) + additionalText;
  if(initialNum === finalNum + 1) {
    clearInterval(counter);
  }
}, 100);
.container {
  text-align: center;
  margin-top: 8em;
}

.number {
  font-weight: 700;
  font-size: 2.5em;
}
<div class="container">
  <h2>Watch as this number rises from 200 to 300</h2>
  <div class="number mt-5">200<span>&nbsp;&nbsp;Your Label</span></div>
</div>

Answer №4

Of course, I'll transform my comments into an answer too :)

@MohammadQasim, check out this idea of appending a string to the counter: http://codepen.io/gc-nomade/pen/OJNympB – G-Cyrillus 7 mins ago

Alternatively, @MohammadQasim, visit http://codepen.io/gc-nomade/pen/yLOYboL if you require the text from HTML – G-Cyrillus 4 mins ago

  • Include another string using innerHTML

const numberEl = document.querySelector('.number');
let startNumber = parseInt(numberEl.innerHTML);
let txt=" My Text";
const endNumber = 200;

const ticker = setInterval(() => {
  numberEl.innerHTML = startNumber++ + txt;
  if(startNumber === endNumber + 1) {
    clearInterval(ticker);
  }
}, 100);
.container {
  text-align: center;
  margin-top: 5em;
}

.number {
  font-weight: 500;
  font-size: 3em;
}
<div class="container">
  <h2>This number will increment from 100 to 200</h2>
  <div class="number mt-3">100 </div>
</div>

  • Or if you prefer to extract it from your HTML template:

const numberEl = document.querySelector('.number');
let startNumber = parseInt(numberEl.innerHTML);
let txt=document.querySelector('.number span').textContent;
const endNumber = 200;

const ticker = setInterval(() => {
  numberEl.innerHTML = startNumber++ + txt;
  if(startNumber === endNumber + 1) {
    clearInterval(ticker);
  }
}, 100);
.container {
  text-align: center;
  margin-top: 5em;
}

.number {
  font-weight: 500;
  font-size: 3em;
}
<div class="container">
  <h2>This number will increment from 100 to 200</h2>
  <div class="number mt-3">100 <span> text I want to keep & see </span></div>
</div>

Answer №5

Here's a helpful tip: to customize the content in your text, simply put it inside another Div with an ID.

<div class="container">
  <div class="number mt-3">
     100        
  </div>
  <div id="changeSubContent">
    **[INSERT YOUR TEXT HERE]** 
  </div>
</div>

After that, you can easily modify the sub-content by using this JavaScript code:

document.getElementById("changeSubContent").innerHTML = "Your Text";

This way, you have full control over the contents of each div according to your preferences.

Answer №6

If you are looking to dynamically add content to the beginning or end of an element, you may want to explore the .insertAdjacentHTML method.

For a more targeted approach within your div, consider incorporating specific elements inside the div to house individual pieces of content, like demonstrated in this code snippet:

const
  numSpan = document.getElementById("numSpan"),
  textSpan = document.getElementById("textSpan");

let countdownNumber = parseInt(numSpan.textContent);
const endNumber = 0;

const ticker = setInterval(() => {
  numSpan.textContent = countdownNumber--;
  if (countdownNumber === endNumber - 1) {
    showBlastoff();
    clearInterval(ticker);
  }
}, 200);

function showBlastoff() {
  textSpan.textContent = "-- Blastoff!!!";
}
<div class="container">
  <div class="number mt-3">
    <span id="numSpan">30</span>
    <span id="textSpan">... and counting down ...</span>
  </div>
</div>

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

The drop-down menu is failing to display the correct values in the second drop-down

Having trouble with the update feature in this code. There are 2 textboxes and 2 dropdowns, but when selecting a course code, the corresponding values for the subject are not being posted. Can anyone assist? view:subject_detail_view <script type="te ...

Using TypeScript and webpack 2 to integrate typeahead.js into your project

I am encountering an error message coming from webpack. ERROR in ./wwwroot/js/admin/infrastructure/typeaheadComponent.ts Module not found: Error: Can't resolve 'typeahead' in ... I have the following dependencies installed npm install ...

Using jQuery to retrieve the location of an element with a specific class

I am working on a slider that adds a class (.current-item) to each active tab and removes it when it's inactive. I am looking to incorporate the LavaLamp effect for the menu, but I am having trouble getting the position of each element with the curren ...

Choosing the type attribute of an input tag by using a javascript variable as a condition: What's the best approach?

I am currently utilizing an input tag on the client side to receive text input. <input type="text" class="form-control" placeholder="Enter Message" id="messageText" autofocus/> My goal now is to dynamically set the type attribute based on a Javasc ...

The Issue of Missing HTML Registration Form Data in Django

My configurations in demo\urls.py, user\urls.py, views.py, and HTML form seem to be set up correctly. However, upon pressing the submit button on the HTML form, I encounter a "File Not Found" error. Even after seeking assistance from ChatGPT, fol ...

Add Firebase Data to Dropdown

Utilizing Vuetify to build a dropdown has been an interesting challenge for me. While I can successfully select a value and store it in the firebase database, I'm facing difficulties when it comes to repopulating the dropdown after page refresh. Belo ...

Bootstrap dropdown menu fails to expand

I recently attempted to implement a hamburger menu using Bootstrap on my website. After checking and adding the necessary CSS and JS files, I encountered an issue where the menu wasn't expanding as expected. I followed the example code provided on the ...

Passing Parameters to Razor Pages Controller

Within my controller, there exists a function as follows: public ActionResult AddSubSub(int? idOfSubsub) { return RedirectToAction("Index", new { searchword = "" }); } I am able to invoke this function without providing any parameter. I attempted the ...

Soft keyboard on mobile fails to update when arrows are used in Ajax-populated dropdown menus

I am working on a web form that includes two select fields: Country and City: <select id="country" onchange="getCity(this);"> <option value="">-- Please select your country --</option> <option value="1">Austria& ...

Combining DataTables with multiple tables sourced from various JSON arrays

I am trying to display data from two different arrays within the same JSON source in two separate tables, but my code seems to be malfunctioning. JSON Information: { "Policies": [ { "name": "A", "id": "1", "score": "0" } ], ...

Obtain the server-side cookie within the getServerSideProps function in Next.js

Attempting to implement authentication on my Next.js website. I've set up a signin endpoint at /api/users/signin where, upon verifying the user, a JWT token is generated and saved as follows: res.setHeader("Set-Cookie", `token=${token}; Htt ...

Tips for accessing .js variables in .ejs files

I am facing an issue with my index.js and list.ejs files in Express. Here is the relevant code: index.js: const express = require("express"); const app = express(); app.set("view engine", "ejs"); app.set("views", __dirname + "\\views"); let ...

Element within an element should be centered

I've been attempting to center a block element, specifically the WordPress caption box with an image, and I'm encountering difficulties. Here is what I have tried: .imagecenter { margin-left: auto; margin-right: auto; display: block; } ...

unable to respond when clicking an angularjs link

I'm facing an issue where I can't get a link to respond to click events in AngularJS. When I click on the anchor link, nothing happens. Here is a snippet of the AngularJS script: <script data-require="<a href="/cdn-cgi/l/email-protection" ...

Performing a modulo operation within a v-for loop

I'm showcasing divs in a loop and I need to assign classes based on the loop index. My goal is to have index 0 and 1 with the class col-6, then indexes 2,3,4 with the class col-4, followed by index 5 and 6 having the class col-6, and so forth. This w ...

Tips for sequentially calling multiple await functions within a for loop in Node.js when one await is dependent on the data from another await

I am currently facing a challenge where I need to call multiple awaits within a for loop, which according to the documentation can be performance heavy. I was considering using promise.all() to optimize this process. However, the issue I'm encounterin ...

The Express.js main router is functioning properly, however, the other routers connected to it are experiencing

I'm encountering an issue with my routers. The main route /weather is working fine, but other routes connected to it are not functioning properly. app.js const express = require('express'); const weatherRoute = require('./back/routes/w ...

React in response after waiting for the DOM element - Reactjs

Hey there! I'm working with a class component that looks like this: class SomeComponent extends Component { componentDidMount = () => { const divElement = document.getElementbyId('id'); // it may take a few moments for this ele ...

AngularJS - Filter out items from ng-repeat that match specific string criteria

After successfully cleaning up an external JSON URL feed by removing unnecessary special characters through a filter in my AngularJS code, I am now faced with the challenge of filtering out specific items from an ng-repeat based on a certain string. angul ...

Stop Bootstrap from impacting a specific division on my webpage

Is there a way to stop Bootstrap from impacting a specific div and its nested divs in my HTML document? Since adding Bootstrap, the images inside this particular div have turned dull and acquired an undesirable blue tint. Thank you for considering my conce ...