Home > Net >  Highlighting Part of a Result
Highlighting Part of a Result

Time:02-02

I'm trying to highlight ONLY the variables: principal, rate, interest, year in the return statement of the compute function. It is required of me that all styling must be in the CSS file only. No inline or internal stylesheets are allowed. All code must be in the JavaScript file only. I have created the highlight class in CSS but this highlights the whole sentence and I don't know how to only highlight parts of a return statement without using inline.

Could someone please help/guide me to know how it's done cause I'm new to using these languages? Would be much appreciated.

Kindly find the HTML, CSS, and JavaScript code below.

HTML CODE

<!--- On clicking the button it computes the interest by calling the compute() function --->
<button onclick="compute()">Compute Interest</button><br><br>
<!--- Show computation result --->
<span id="result" class = "highlight"></span>

CSS CODE

/* Highlights the result */
.highlight {
    background-color: yellow;
}

JAVASCRIPT CODE

/* Function that computes and returns the result */
function compute()
{
    /* some code */
   
 return document.getElementById("result").innerHTML="If you deposit " principal ",\<br\>at an interest rate of " rate "%\<br\>You will receive an amount of " interest ",\<br\>in the year " year "\<br\>";
}

CodePudding user response:

For this to work you would need span-elements with the class highlight around you're variables. For semantics it might be better if the element with the id result is a p-element or something similar.

Also as @user1599011 pointed out, your Javascript needs to do something, it needs to execute a command, not return it.

A working solution:

let principal = '1000';
let rate = '10';
let interest = '100';
let year = '2022';

/* Function that computes and returns the result */
function compute()
{
  document.getElementById("result").innerHTML= 'If you deposit <span >'  principal  '</span>, <br>at an interest rate of <span >'  rate  '%</span><br>You will receive an amount of <span >'  interest  '</span>, <br>in the year <span >'  year  '</span><br>';
}
/* Highlights the result */
.highlight {
    background-color: yellow;
}
<!--- On clicking the button it computes the interest by calling the compute() function --->
<button onclick="compute()">Compute Interest</button>
<!--- Show computation result --->
<p id="result"></p>

  •  Tags:  
  • Related