Replacing old with new in JavaScript

General Tech Learning Aids/Tools 2 years ago

0 2 0 0 0 tuteeHUB earn credit +10 pts

5 Star Rating 1 Rating

Posted on 16 Aug 2022, this text provides information on Learning Aids/Tools related to General Tech. Please note that while accuracy is prioritized, the data presented might not be entirely correct or up-to-date. This information is offered for general knowledge and informational purposes only, and should not be considered as a substitute for professional advice.

Take Quiz To Earn Credits!

Turn Your Knowledge into Earnings.

tuteehub_quiz

Answers (2)

Post Answer
profilepic.png
manpreet Tuteehub forum best answer Best Answer 2 years ago

 

Ok, let me be more specific; I am making a simple Celsius to Fahrenheit, and Fahrenheit to Celsius converter aid in my learning of JavaScript.

So, I have successfully made the converter work, and have it displayed in the DOM using new 'p' elements (which I will be later adding a border around in CSS).

But what I am struggling with is having the new converted number cover the old one.

Right now, you enter a number, it gives you the conversion(inside a 'p' element), then when you convert the next number, it gives you another. Until their is a list of conversions.

What would I write into my code so that when you press "enter" the old result is replaced with the new?

Here is the code thus far (I know it is probably very basic but I am very new to JavaScript):

            var celToFaren = {
        celcius: function(convert) {
            var c = Number(document.getElementById("celCount").value);
            var e = c * 9/5 + 32;
            if (c === 0) {
                alert('Please Enter a Number');
                return false;
            } else {
            var element = document.getElementById('div1');
            var resultShow = document.createElement('p');
            resultShow.textContent = c + ' ' + 'Celcius ' + 'is equal to ' + e + ' Farenhite';

            element.appendChild(resultShow);

            }
        }
    };
profilepic.png
manpreet 2 years ago

In your code, you are every time creating a new element and appending each time.

var resultShow = document.createElement('p');

What you need to do is create a blank 'p' element with an identifier and re-use it. Eg. 

id="result">

Then on every enter instead of creating a new element, just use javascript selector method to replace the new value. Eg. document.querySelector("#result").innerHTML = "new calculated value";

Hope this helps.


0 views   0 shares

No matter what stage you're at in your education or career, TuteeHub will help you reach the next level that you're aiming for. Simply,Choose a subject/topic and get started in self-paced practice sessions to improve your knowledge and scores.