Javascript var html element

JavaScript Variables

In this first example, x , y , and z are undeclared variables.

They are automatically declared when first used:

Example

Note

It is considered good programming practice to always declare variables before use.

From the examples you can guess:

Example using var

Note

The var keyword was used in all JavaScript code from 1995 to 2015.

The let and const keywords were added to JavaScript in 2015.

The var keyword should only be used in code written for older browsers.

Example using let

Example using const

Mixed Example

The two variables price1 and price2 are declared with the const keyword.

These are constant values and cannot be changed.

The variable total is declared with the let keyword.

The value total can be changed.

When to Use var, let, or const?

1. Always declare variables

2. Always use const if the value should not be changed

3. Always use const if the type should not be changed (Arrays and Objects)

4. Only use let if you can’t use const

5. Only use var if you MUST support old browsers.

Just Like Algebra

Just like in algebra, variables hold values:

Just like in algebra, variables are used in expressions:

From the example above, you can guess that the total is calculated to be 11.

Note

Variables are containers for storing values.

JavaScript Identifiers

All JavaScript variables must be identified with unique names.

These unique names are called identifiers.

Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).

The general rules for constructing names for variables (unique identifiers) are:

  • Names can contain letters, digits, underscores, and dollar signs.
  • Names must begin with a letter.
  • Names can also begin with $ and _ (but we will not use it in this tutorial).
  • Names are case sensitive (y and Y are different variables).
  • Reserved words (like JavaScript keywords) cannot be used as names.

Note

JavaScript identifiers are case-sensitive.

The Assignment Operator

In JavaScript, the equal sign ( = ) is an «assignment» operator, not an «equal to» operator.

This is different from algebra. The following does not make sense in algebra:

In JavaScript, however, it makes perfect sense: it assigns the value of x + 5 to x.

(It calculates the value of x + 5 and puts the result into x. The value of x is incremented by 5.)

Note

The «equal to» operator is written like == in JavaScript.

JavaScript Data Types

JavaScript variables can hold numbers like 100 and text values like «John Doe».

In programming, text values are called text strings.

JavaScript can handle many types of data, but for now, just think of numbers and strings.

Strings are written inside double or single quotes. Numbers are written without quotes.

If you put a number in quotes, it will be treated as a text string.

Example

Declaring a JavaScript Variable

Creating a variable in JavaScript is called «declaring» a variable.

You declare a JavaScript variable with the var or the let keyword:

After the declaration, the variable has no value (technically it is undefined ).

To assign a value to the variable, use the equal sign:

You can also assign a value to the variable when you declare it:

In the example below, we create a variable called carName and assign the value «Volvo» to it.

Then we «output» the value inside an HTML paragraph with >

Example

let carName = «Volvo»;
document.getElementById(«demo»).innerHTML = carName;

Note

It’s a good programming practice to declare all variables at the beginning of a script.

One Statement, Many Variables

You can declare many variables in one statement.

Start the statement with let and separate the variables by comma:

Example

A declaration can span multiple lines:

Example

Value = undefined

In computer programs, variables are often declared without a value. The value can be something that has to be calculated, or something that will be provided later, like user input.

A variable declared without a value will have the value undefined .

The variable carName will have the value undefined after the execution of this statement:

Example

Re-Declaring JavaScript Variables

If you re-declare a JavaScript variable declared with var , it will not lose its value.

The variable carName will still have the value «Volvo» after the execution of these statements:

Example

Note

You cannot re-declare a variable declared with let or const .

JavaScript Arithmetic

As with algebra, you can do arithmetic with JavaScript variables, using operators like = and + :

Example

You can also add strings, but strings will be concatenated:

Источник

How to Use Javascript Variable in HTML

You can only use Javascript variable in HTML by linking the Javascript variable to a HTML element using an id or class attribute.

Linking Javascript Variable to HTML Element

Assign an id to the element.

 id="content-holder">Content is loading . 

If you check this now all you will see is:

HTML text placeholder screenshot

You can now add Javascript to your page using script tags.

 // Write your Javascript code inside here  

Now, you can start working on the Javascript. Create your Javascript Variable.

var newContent = "This content will be loaded as a paragraph on the p tag when we add it through Javascript."; 

You grab the element in Javascript using the assigned id value.

var contentHolder = document.getElementById('content-holder'); 

To display the variable in HTML, assign the variable to the element in Javascript using the innerHTML property.

contentHolder.innerHTML = newContent; 

Display Javascript Variable in HTML screenshot

Complete Code

 id="content-holder">Content is loading . // Write your Javascript code inside here var newContent = "This content will be loaded as a paragraph on the p tag when we add it through Javascript."; var contentHolder = document.getElementById('content-holder'); contentHolder.innerHTML = newContent;  

You can use the above method for string and number variables.

Using Javascript Array Variable in HTML

To view array and object variables in HTML, you have to loop through the items in Javascript before passing them to HTML.

Display Javascript array variable in HTML screenshot

You can also interact with the code for this project.

author

Hi there! I am Avic Ndugu.

I have published 100+ blog posts on HTML, CSS, Javascript, React and other related topics. When I am not writing, I enjoy reading, hiking and listening to podcasts.

Front End Developer Newsletter

Receive a monthly Frontend Web Development newsletter.
Never any spam, easily unsubscribe any time.

About

If you are just starting out you can test the waters by attempting the project-based HTML tutorial for beginners that I made just for you.

Okay, you got me there, I made it because it was fun and I enjoy helping you on your learning journey as well.

You can also use the HTML and CSS projects list as a source of projects to build as you learn HTML, CSS and JavaScript.

Start understanding the whole web development field now

Stop all the confusion and start understanding how all the pieces of web development fit together.

Never any spam, easily unsubscribe any time.

Recent Posts

Copyright © 2018 — 2023 DevPractical. All rights reserved.

Источник

How to display JavaScript variable value in HTML

This tutorial will show you how to use all three ways to display JavaScript variables in HTML pages. Let’s start with using document.write() method.

Display JavaScript variable using document.write() method

The document.write() method allows you to replace the entire content of HTML tag with HTML and JavaScript expressions that you want to be displayed inside the tag. Suppose you have the following HTML element:

When you run document.write("Hello") method on the HTML piece above, the content of will be replaced as follows:
 Knowing this, you can display any JavaScript variable value by simply passing the variable name as the parameter to document.write() method:

The document.write() method is commonly used only for testing purposes because it will delete any existing HTML elements inside your tag. Mostly, you would want to display a JavaScript variable beside your HTML elements. To do that, you need to use the next method.

Display JavaScript variable using innerHTML property.

Every single HTML element has the innerHTML property which holds the content of that element. The browser allows you to manipulate the innerHTML property by using JavaScript by simply assigning the property to a different value.

For example, imagine you have the following HTML tag:

 You can replace the content of 

tag by first retrieving the element using its identifier. Since the element

has an id attribute with the value of greeting , you can use document.getElementById method to retrieve it and change its innerHTML property.

The content of 

tag will be changed as follows:

Knowing this, you can simply wrap the space where you want your JavaScript variable to be displayed with a element as follows:
The code above will output the following HTML:
And that’s how you can display JavaScript variable values using innerHTML property.

Display JavaScript variable using window.alert() method

The window.alert() method allows you to launch a dialog box at the front of your HTML page. For example, when you try running the following HTML page:

The following dialog box should appear in your browser:

The JavaScript alert box example

The implementation for each browser will slightly vary, but they all work the same. Knowing this, you can easily use the dialog box to display the value of a JavaScript variable. Simply pass the variable name to the alert() method as follows:

 The code above will launch a dialog box that displays the value of the name variable.

Conclusion

Displaying JavaScript variables in HTML pages is a common task for web developers. Modern browsers allow you to manipulate the HTML content by calling on exposed JavaScript API methods.

The most common way to display the value of a JavaScript variable is by manipulating the innerHTML property value, but when testing your variables, you can also use either document.write() or window.alert() methods. You are free to use the method that suits you best.

Learn JavaScript for Beginners 🔥

Get the JS Basics Handbook, understand how JavaScript works and be a confident software developer.

A practical and fun way to learn JavaScript and build an application using Node.js.

About

Hello! This website is dedicated to help you learn tech and data science skills with its step-by-step, beginner-friendly tutorials.
Learn statistics, JavaScript and other programming languages using clear examples written for people.

Type the keyword below and hit enter

Tags

Click to see all tutorials tagged with:

Источник

Display JavaScript Variable In HTML

In this tutorial we will see how to Display JavaScript Variable In HTML. The innerHTML property and document.write() can be used to display the JS variable inside the HTML page or document.

Using document.write()

document.write() is used to write HTML expression or JavaScript code to the HTML document. We can also use document.write() to display JavaScript Variable in HTML.

Code

JavaScript Code and HTML Code is given below, In this code we have used document.write() inside the paragraph tag to display the value of our JavaScript variable.

  

I Love

Using innerHTML property

The innerHTML property sets or returns the content of HTML tags. It can also be used to display the value of JavaScript variable in HTML.

HTML Code

HTML Code is given below, In this code we have one paragraph element with .

JavaScript Code

Take a look at the JavaScript code, in this example we have a variable named ‘number‘.

First document.getElementById() method is used to target the paragraph element, then .innerHTML method is used to display the JavaScript variable inside the paragraph tag.

  

Demo

Video Tutorial

Watch video tutorial on how to Display JavaScript Variable In HTML.

Источник

Читайте также:  Php очистить содержимое папки
Оцените статью