Your declaration is fine, but the assignment part is missing document
as the object which has the .getElementById
method. Then, once you have the reference to the element, you then need to access its content with .textContent
(you can't compare the entire element to a value that the element might contain). As a side note on this, when the string you wish to set/get doesn't contain any HTML, you should use .textContent
so that the browser doesn't parse the string for HTML unnecessarily. Often, people will suggest that the content of an element should be gotten/set using .innerHTML
and, while that will work, it's wasteful if the string doesn't contain any HTML.
Also, the <script>
must be located within the head
or the body
, not outside of them. I would suggest placing it just prior to the closing body
tag so that by the time the processing reaches the script
, all of the HTML elements have been parsed into memory and are available.
Lastly (and this is really just a side point), an HTML page also needs the title
element to have something in it, otherwise it won't be valid. While browsers don't actually do HTML validation, it's important to strive for valid HTML so that you can be sure that your pages will work consistently across all devices. You can validate your HTML at: http://validator.w3.org.
<!DOCTYPE html>
<html>
<head>
<title>Something Here</title>
</head>
<body>
<p id="sample">a</p>
<script type="text/javascript">
var sample = document.getElementById('sample');
if (sample.textContent == "a") {
alert("Correct")
};
</script>
</body>
</html>