Home  >  Article  >  Web Front-end  >  How to use innerHTML in JavaScript

How to use innerHTML in JavaScript

不言
不言Original
2018-12-22 11:03:3637341browse

The innerHTML attribute allows you to change the content of the html element. You can set or return the HTML between the start and end tags of the table row. This article will introduce you to the usage of innerHTML. Let’s go See the specific content.

How to use innerHTML in How to use innerHTML in How to use innerHTML in JavaScript

How to write innerHTML

For element, set the element name specified by innerHTML.

element.innerHTML;

Assign the html code of the specified element to the variable

By writing as follows, we assign the html code of the specified element to the variable sample1

var sample1 = element.innerHTML;

Replace the value of the variable with the specified element

Writing as follows, you can display the content of the variable sample2 on the element element after deleting the content of the element element.

element.innerHTML = sample2;

Clear the specified element

You can clear the content of the element element by specifying "".

element.innerHTML = “”;

Let’s look at the specific examples of innerHTML usage

The basic code is as follows

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title></title>
</head>
<body>
<div id="txt">
      <div id="txt1">文字内容1 </div>
      <span id="txt2">文字内容2 </span>
    </div>
    <p>---------------------</p>
    <div id="innerHTMLtxt"></div>
</body>
</html>

The running results are as follows

How to use innerHTML in How to use innerHTML in How to use innerHTML in JavaScript

Let’s look at the results of using the innerHTML attribute

<script type="text/javascript">
		innerHTMLtxt.innerHTML="php中文网!";
	</script>


##The running results are as follows

How to use innerHTML in How to use innerHTML in How to use innerHTML in JavaScript

Then let’s look at the code that uses innerHTML to clear elements

<script>
  txt.innerHTML="";
</script>

The running results are as follows

How to use innerHTML in JavaScript

This article ends here, more For exciting content, you can pay attention to the relevant columns of php Chinese website! ! !


The above is the detailed content of How to use innerHTML in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn