Как из js передать переменную в html
Перейти к содержимому

Как из js передать переменную в html

  • автор:

Как вывести переменную из js в html

Аватар пользователя Вячеслав Межуревский

В самом простом случае, сначала необходимо в html документе дать элементу в который будем помещать данные — id или класс. Например:

Затем, ниже объявленного искомого объекта, в теле тега <script> необходимо с помощью JavaScript "получить" объект и занести в свойство textContent необходимые данные.

How to display JavaScript variables in a HTML page without document.write

I am trying to display some JavaScript variable on my HTML page.

I was first using document.write() but it use to overwrite the current page when the function was called.

After searching around, the general consensus was that document.write() isn’t liked very much. What are the other options?

I found a page suggesting using .innerHTML but that was written in 2005.

A jsFiddle illustrating my problem http://jsfiddle.net/xHk5g/

9 Answers 9

Element.innerHTML is pretty much the way to go. Here are a few ways to use it:

JavaScript

If you just want to update a portion of a <div> I usually just add an empty element with a class like value or one I want to replace the contents of to the main <div> . e.g.

Then I’d use some code like this:

Then the HTML/DOM would now contain:

Full example. Click run snippet to try it out.

You can use javascript to access elements on the page and modify their contents. So for example you might have a page with some HTML markup like so:

You can use javascript to change the content like so.

You can also look at using the JQuery javascript library for DOM manipulation, it has some great features to make things like this very easy.

For example, with JQuery, you could do this to acheive the same result.

Based on this example you provided in your post. The following JQuery would work for you:

Using a P tag like this however is not recommended. You would ideally want to use an element with a unique ID so you can ensure you are selecting the correct one with JQuery.

https://amdy.su/wp-admin/options-general.php?page=ad-inserter.php#tab-8

How to display JavaScript variable value in HTML

There are three ways to display JavaScript variable values in HTML pages:

  • Display the variable using document.write() method
  • Display the variable to an HTML element content using innerHTML property
  • Display the variable using the window.alert() method

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 <body> tag with HTML and JavaScript expressions that you want to be displayed inside the <body> tag. Suppose you have the following HTML element:

When you run document.write("Hello") method on the HTML piece above, the content of <body> 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 <body> 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 <body> tag:

You can replace the content of <p> tag by first retrieving the element using its identifier. Since the element <p> has an id attribute with the value of greeting , you can use document.getElementById method to retrieve it and change its innerHTML property.

Here’s how you do it:

The content of <p> 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 <span> 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 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.

Get 100 JavaScript Snippets Book for FREE ��

100 JavaScript snippets that you can use in various scenarios

Save 1000+ hours of research and 10x your productivity

Ezoic

report this ad

About

Sebhastian is a site that makes learning programming easy with its step-by-step, beginner-friendly tutorials.
Learn JavaScript and other programming languages with clear examples.

Free Code Snippets Book

Get my FREE code snippets Book to 10x your productivity here

Ezoic

report this ad

Search

Type the keyword below and hit enter

Click to see all tutorials tagged with:

Ezoic

report this ad

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *