Why Isn't this a part of HTML and JavaScript?


#1

Hi,

I am trying out event driven programs, and here is one of the things I was trying to do

< body>
< script>
var number = 100;
</ script>
< p> number< /p>
< /body>

But then i soon realized you cannot use variable names inside of <p>, and transfer the value of those variables. The output was:

number

Using a variable like this seems very logical, so why is using variables outside of the < script> tags not a thing? Or am I missing something? are there other ways of doing this?


#2

Because the <script> tag defines the code as script, JS code can ONLY work inside of the <script> tag. Therefore, when you tried to reference the variable number outside of the <script> tag, it treated it as HTML, not JS. In order to use JS to modify HTML elements, you have to use JQuery inside of the script tag, or as imported script.


#3

no idea what jQuery or imported script are, what thanks!


#4

@dantemp, you can use js to manipulate html, jquery might be easier, but js is most certainly possible.

@dr_palsonph_d, jquery is a library written in javascript to make manipulating html easier. You can import this library in your code, of course, this means you need to learn the syntax first


#5

FYI if you wanted to make the p tag contain the value of the variable number, this is the way I prefer to do it in plain JS:

<body>
    <p id="one"></p> <!-- Make sure that the paragraph is above the script-->
    <script>
        var number = 100;
        document.getElementById("one").innerHTML = number;
    </script>
</body>

#6

You can of course upgrade this code:

<head>
    <script>
    function myFunction(){
        var number = 100;
        document.getElementById("one").innerHTML = number;
    }
    </script>
</head>
<body> 
    <input type="button" value="click me" onclick="myFunction()">
    <p id="one"></p> 
</body>

#7

That's what I was thinking! But I think we should keep it basic, because that's what it looked like it was supposed to be, not a button, just a paragraph containing "100".


#8

Good point, but a demonstration with what is possible is also cool :slightly_smiling:


#9

@stetim94 I apologize for not making myself clearer. I did not mean that JQuery was the only way, simply the best. I used JS to do that sort of thing for quite a while, before I learned JQuery.


#10

That depends on personal preference.


#11

how do you guys write code into the forums? for example:

I have to do this < p> fahfa </ p> so that the the 2 < P> show up, if I dont leave the spaces than they just dont show up for example: I will write < p> fahafafh </ p> the correct way:

fahafafh

--see how it didn't show the < p> </ P>

#12

3 backticks before and after:

```
<p>Visible</p>
```

#13

thanks mate! really helps