0

I found this script which is perfect for what I need. However I would like to change the font properties to make it bold and red for the result displayed. I looked all over and tried adding it but somehow I just seem to make it not function at all when I do. Any help is greatly appreciated. Here is my script.

<script type="text/javascript">
    var currentValue = 35;
    var add = function(valueToAdd){
        currentValue += valueToAdd;
        document.getElementById('number').innerHTML = currentValue;

    };
</script>

3 Answers 3

0

Use setAttribute to this element in DOM tree:

<script type="text/javascript">
    var currentValue = 35;
    var add = function(valueToAdd){
        currentValue += valueToAdd;
    var el = document.getElementById('number');
        el.innerHTML = currentValue;
        el.setAttribute('style', 'font-weight:bold; color:red;')
    };
</script>
3
  • This is perfect. I am very grateful thank you so much!
    – Peredy
    Nov 27, 2020 at 19:48
  • Not to be a pain, but I just realized this isn't saved on the webpage. I need to be able to have this saved so when 1 is added or removed, then the new number is visible when someone else goes to the page. Here is the link of what I have so far: peredyizhere.com/ppreq/donocount.html
    – Peredy
    Nov 27, 2020 at 20:42
  • If you you mean case when user 1 set value from 35 to 30 and close page. And user 2 after that open page page and see 30.. You need send your changes to server and get back from it on page load.. Nov 28, 2020 at 12:39
0

I would recommend getting the element and storing it in a variable for easier use.

<script type="text/javascript">
    var currentValue = 35;
    var add = function(valueToAdd){
        var elem = document.getElementById('number');
        currentValue += valueToAdd;
        elem.style.color = 'red';
        elem.style.fontWeight = "bold";
        elem.innerHTML = currentValue;
    };
</script>

Not recommended but this is without an element variable above is cleaner and better code

<script type="text/javascript">
    var currentValue = 35;
    var add = function(valueToAdd){
        currentValue += valueToAdd;
        document.getElementById('number').style.color = 'red';
        document.getElementById('number').style.fontWeight = "bold";
        document.getElementById('number').innerHTML = currentValue;
    };
</script>
0

You can use style attribute to update the styles:

document.getElementById('number').style.color = 'red';
document.getElementById('number').style.fontWeight = 'bold';

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.