I have an HTML webpage that gets a number from an external javascript using this:
<span id="numl"></span>
but I want to add the number 10 to the generated number, how can I do this, for example, the code above gets number "8" but instead of showing "8" it should add 10 to it which would be equals to "18"
I'm new to javascript and don't know how to do this
The following code should increment the number by ten.
To resolve the timing issue you can use a Mutation Observer to change the number as soon as it is changed.
//source: https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver/observe
// identify an element to observe
const elementToObserve = document.getElementById("num1");
//global variable to monitor changecount
window.changeCount = 0;
// create a new instance of `MutationObserver` named `observer`,
// passing it a callback function
const observer = new MutationObserver(function() {
if(window.changeCount == 0) //so it wont recursively increment by 10
{
element = document.getElementById("num1");//get Element
element.innerText = parseInt(element.innerText) + 10; //increment innerText by 10
}
window.changeCount = window.changeCount + 1; //increment change count by one
});
// call `observe()` on that MutationObserver instance,
// passing it the element to observe, and the options object
observer.observe(elementToObserve, {subtree: true, childList: true});