0

I don't know how to declare a variable here in javascript. I have an example situation that if the paragraph is equals to a, the alert will popup.

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<p id="sample">a</p>
</body>
</html>

<script type="text/javascript">
    var sample = getElementById('sample');

    if (sample == "a") {
        alert("Correct")
    };
</script>
chazsolo
  • 7,873
  • 1
  • 20
  • 44
  • Uhmm... What's the question here? – gforce301 Apr 06 '18 at 16:24
  • How to declare a variable, and how to deliver it? – Spencer Sanchez Apr 06 '18 at 16:25
  • 2
    In your code `sample` is an html element, not the text from inside it. – takendarkk Apr 06 '18 at 16:26
  • 1
    This is not a place to learn programming. This is a place to discuss and solve programming problems. [I recommend this if you are finding an online tutorial](https://www.w3schools.com/js/default.asp). – yqlim Apr 06 '18 at 16:26
  • There are multiple syntax error in the code. Do some javascript beginners course that will be helpful. – Subir Kumar Sao Apr 06 '18 at 16:26
  • 1
    @YongQuan Don’t recommend W3Schools. Their content is often inaccurate, outdated and incomplete. Use [MDN](https://developer.mozilla.org/en-US/docs/Web) instead. – Sebastian Simon Apr 06 '18 at 16:29
  • 1
    @Xufox that was many many years ago. Their content now is good enough for beginner and their environment is very beginner friendly. MDN is too complicated for a complete beginner. – yqlim Apr 06 '18 at 16:30
  • 3
    @YongQuan That's incorrect. It's still as bad as ever - maybe worse. Use MDN instead. – Scott Marcus Apr 06 '18 at 16:34
  • @ScottMarcus try it yourself before commenting – yqlim Apr 06 '18 at 16:36
  • 1
    @YongQuan Yeah, … sorry, I don’t see it. W3Schools still lags miles behind MDN. They _apparently_ became better over the last few years, but it’s still absolutely not “good enough” now and potentially misleading, especially for beginners. – Sebastian Simon Apr 06 '18 at 16:37
  • 2
    @YongQuan ??? I've been looking at it since it came online. Can I comment now? – Scott Marcus Apr 06 '18 at 16:38
  • @ScottMarcus Even w3fools from where you got this image of w3schools has changed its stance. You all should also change now and re read http://www.w3fools.com/. It does not hate w3schools anymore and it is fine to recommend that – bugwheels94 Apr 06 '18 at 16:42
  • 3
    @YongQuan I got my stance from looking at W3Schools. Please don't make assumptions about what others know and where they got that knowledge. Recommend what you want. It's up to you to ignore good advice. – Scott Marcus Apr 06 '18 at 16:44
  • @Xufox try explaining thermodynamics to a 5 year-old child. They wouldn’t understand a thing until they are at least in high school, unless you explain it to them using a completely misleading way in a college student perspective. – yqlim Apr 06 '18 at 16:45
  • 1
    @ScottMarcus as mentioned by bugswheels94, please reread w3fools, if that even concerns you. – yqlim Apr 06 '18 at 16:46
  • 2
    @YongQuan It doesn't. I don't need a site to tell me that another site is good or bad. I can just look at a site and tell for myself. – Scott Marcus Apr 06 '18 at 16:48
  • @ScottMarcus ok – yqlim Apr 06 '18 at 16:52
  • @ScottMarcus May you pleasle provide any example where w3schools is still misinforming? I learned from w3schools 6 years ago when it was bad and now it looks fine to me. It may be very brief which is good for beginners as not everybody can handle a lot of info at start – bugwheels94 Apr 06 '18 at 16:52
  • @bugwheels94 I don't document errors at W3 Schools, nor am I going to waste my time searching for some. But, I will tell you that I have been a professional IT trainer for over 25 years and consistently (to this day), students will pull up W3 Schools and ask me questions about what they are seeing. And, very often when that happens, I see that the site is incorrect. Usually it relates to the browser compatibility tables or to the descriptions not being accurate. The code may work, but if you leave the site with an incorrect understanding of what the code does or where it can be used, it's bad. – Scott Marcus Apr 06 '18 at 18:51
  • @ScottMarcus As short as I can be: the above statement is not correct anymore given the lack of evidence and just conclusion based upon years. Check this out: http://dilbert.com/strip/2010-12-23 – bugwheels94 Apr 07 '18 at 02:31
  • @bugwheels94 I really don't see why you seem to feel that you can tell me what my experience is and has been. I told you that the errors persist ***to this day***. If you like it, go for it, but that doesn't change ***actual*** facts. – Scott Marcus Apr 07 '18 at 13:04

3 Answers3

2

You're declaring your variable just fine, however if you want the text within the element, you also need to use the innerHTML property. And when you use the getElementById method, you need to use it on the document object like document.getElementById:

var sample = document.getElementById('sample');

if (sample.innerHTML == "a") {
  alert("Correct")
};
<p id="sample">a</p>
j08691
  • 204,283
  • 31
  • 260
  • 272
0

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>
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
  • @SpencerSanchez You're welcome. Please up vote all helpful answers and consider marking this one as "the" answer (it is more correct than all the others). – Scott Marcus Apr 06 '18 at 16:31
  • I fail to see how your answer "is more correct than all the others" simply because you chose to use textContent – j08691 Apr 06 '18 at 16:32
  • @j08691 `.innerHTML` is incorrect here and my answer addresses the incorrect location of the `script` element, which no other answer does. – Scott Marcus Apr 06 '18 at 16:33
  • Correct position is under head element, is not it? And then defer or async. This is weird that we are discussing over this – bugwheels94 Apr 06 '18 at 16:35
  • 1
    @bugwheels94 `script` may go in the `head` or `body`. If it goes in the head, you may opt to use `defer` or `async` or neither and set up a `DOMContentLoaded` event handler. Or, you can avoid all of that and just place it just before the closing `body` tag, which eliminates the need for that additional code and/or setting up an event handler. It's quite common to take this approach. – Scott Marcus Apr 06 '18 at 16:37
0

sample is a variable and you are correct but it is storing a reference to a DOM Element with id sample. To get the inner html of that you need

var sample = getElementById('sample').innerHTML;

Also, use === over == for no casting etc. Refer here

I will recommend you to have a quick look at JS from w3schools and then move to MDN. Nobody will report you here if you show your efforts, so relax :).

bugwheels94
  • 30,681
  • 3
  • 39
  • 60