0

I am basically trying to have a number displayed that starts at 0 and goes up randomly every time you press a button. But I need a variable to equal the current number(which is stored within an h1 tag). How do I do that? Currently when I try to check if it worked by alerting the page, all I get is [object HtmlHeadingElement] Here is my JavaScript, CSS, and HTML code, respectively:

function myRandom() {
  var headnumber = document.getElementById('headnum');
  alert(headnumber)
    //the alert is just to check if '0' comes up'
}
 

h1 {
  text-align: center;
  font-size: 30px;
  color: blue;
  font-family: Verdana;
}
button {
  margin-left: 640px;
  border: solid blue 5px;
  font-size: 14px;
  font-family: Verdana;
  font-weight: bold;
  background-color: cyan;
  border-radius: 6px;
}
<h1 id='headnum'>3</h1>
<button onclick="myRandom()">Button</button>

1
  • Do this: var headnumber = +document.getElementById('headnum').textContent; Commented Apr 19, 2016 at 23:14

2 Answers 2

4

You could get the html content using innerHTML. See below,

function myRandom() {
  var headnumber = document.getElementById('headnum').innerHTML;
  alert(headnumber)
    //the alert is just to check if '0' comes up'
}
h1 {
  text-align: center;
  font-size: 30px;
  color: blue;
  font-family: Verdana;
}
button {
  margin-left: 640px;
  border: solid blue 5px;
  font-size: 14px;
  font-family: Verdana;
  font-weight: bold;
  background-color: cyan;
  border-radius: 6px;
}
<h1 id='headnum'>3</h1>
<button onclick="myRandom()">Button</button>

Sign up to request clarification or add additional context in comments.

Comments

2

The assignment of headnumber is to an object returned by the document.getElementById('headnum') function call. In order to get the value inside the object use document.getElementById('headnum').innerHTML

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.