1

I am a newbie in web, now I'm studying JS. I have this simple script to be executed:

<script language="javascript">
var getDate = function() {
    var doc = document.getElementById("demo");
    doc.innerHTML = Date();
}
</script>

And this CSS rule for the label in which the script will be shown:

<style type="text/css">
.cstyle {
    font-family: "Comic Sans MS", cursive;
}
</style>

In my document I have a button that triggers my script

<p id="demo"><span class="cstyle">Result.</span></p>
<button type="button" onClick="getDate()">Display Data</button>

When the document is being loaded "Result" is displayed with "Comic Sans" font. But when the mouse click has been happened, the date is displayed with the default font. This behaviour is abnormal, because script execution result is needed to be displayed with "Comic Sans" font too. How can I fix this?


[Upd.] Sorry for a little mistake, this is doc.innerHTML = Date(); instead of doc.innerHTML = arr.toString();

1
  • when in doubt,inspect the elemnts in live html view in browser console, will see structure and all css rules that apply Commented Nov 17, 2013 at 16:43

3 Answers 3

1

Your style is on the <span> element. When you use change the innerHTML, the <span> element is replaced by the text. You need to update your code to be the following:

HTML:

<p id="demo"><span id="result" class="cstyle">Result.</span></p>

and JS:

var getDate = function() {
    var doc = document.getElementById("result");
    doc.innerHTML = Date();
}
Sign up to request clarification or add additional context in comments.

Comments

0

This is because you are applying the font-family: "Comic Sans MS", cursive on the element with class .cstyle. When clicking on the button, you are replacing the

<span class="cstyle">Result.</span>

with a string value (without the .cstyle class which provides the styling of your desired font).

Just move your class .cstyle on the parent element <p>.

<p id="demo" class="cstyle"><span >Result.</span></p>
<button type="button" onClick="getDate()">Display Data</button>

You can even leave the <span> element, which is not needed in this case.

<p id="demo" class="cstyle">Result.</p>
<button type="button" onClick="getDate()">Display Data</button>

Comments

0

Unfortunately you are replacing the span with the cstyle with just the date. Remember you have selected the p with id demo to insert your result so you simply replace its html using innerHTML. If that paragraph had also the class cstyle then everything would be fine.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.