js get id of content and modify the original content (innerHTML)

js get id of content (getElementById) and modify the original content (innerHTML)

 

 

1. Get elements with ID

Learned HTML / CSS style, know that web page by the label information organized, and the id attribute value of the tag is unique, as is each person has a different ID number, as long as you can find by ID number corresponding to people. So in a web page, we first find the tag by id, then follow.

grammar:

 document.getElementById(“id”) 
 

Consider the following codes:

Results: null or [ Object HTMLParagraphElement]

Note: the acquired element is an object, such as to the elements to operate, we must, through its properties or methods.

 

 

Example:

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>document.getElementById</title>
</head>
<body>
<p id="con">JavaScript</p>
<script type="text/javascript">
  var mychar= document.getElementById('con')          ;
  document.write("结果:"+mychar); //输出获取的P标签。 
</script>
</body>
</html>

 effect:

 

 

 

 

 

2.innerHTML property

innerHTML property gets or replace the content of HTML elements.

grammar:

Object.innerHTML

 

note:

1.Object element object is acquired as acquired by document.getElementById ( "ID") element.

2. Notice of writing, innerHTML case sensitive.

We obtained by id = "con" <p> element and the output element and change the contents of element content, as follows:

result:

 

 Example:

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>innerHTML</title>
</head>
<body>
<h2 id="con">javascript</H2>
<p> JavaScript是一种基于对象、事件驱动的简单脚本语言,嵌入在HTML文档中,由浏览器负责解释和执行,在网页上产生动态的显示效果并实现与用户交互功能。</p>
<script type="text/javascript">
  var mychar= document.getElementById('con')          ;
  document.write("原标题:"+mychar.innerHTML+"<br>"); //输出原h2标签内容
  mychar.innerHTML = 'Hello world!';
  document.write("修改后的标题:"+mychar.innerHTML); //输出修改后h2标签内容
</script>
</body>
</html>

 

结果:

 

Guess you like

Origin www.cnblogs.com/ccw869476711/p/11640723.html