Home > Web Front-end > JS Tutorial > JavaScript controls the web page-getting web page elements_javascript skills

JavaScript controls the web page-getting web page elements_javascript skills

WBOY
Release: 2016-05-16 15:08:21
Original
1390 people have browsed it

Recommended reading: JavaScript Controls Web Pages - DOM

JavaScript controls web pages-CSS and DOM

Use DOM to split HTML

Using JavaScript to control web content is actually a lot like cooking. There is no need to clean up the leftovers, but there is no way to enjoy the delicious results.

However, you will be able to complete the HTML components of web content: more importantly, you will have the ability to replace web page components.

JavaScript allows you to manipulate the HTML code of web pages as you like, thus opening the door to all kinds of interesting opportunities, all because of the existence of the standard object: DOM

getElementById

HTML标签都有一个"id"属性,第个标签的该属性都是独一无二的
可以通过id属性来获取元素
<body>
<div id="div1">
<div id="div2">
内容
</div>
</div>
</body>
var sceneDesc=document.getElementById("div2");
getElementById可以通过元素的id属性去访问标签
括号里是id的值
Copy after login

getElementsByTagName

也可以通过标签名来获取元素
<body>
<div id="div1">
<div id="div2">
<div id="div3">
内容
</div>
</div>
</div>
</body>
var divs=document.getElementsByTagName("div");
getElementsByTagName返回所有div标签,结果是一个数组,结果按照标签在HTML中的顺序排列
括号里是标签名
var divs=document.getElementsByTagName("div")[2];
用索引获取第三个div标签
Copy after login

innerHTML

innerHTML特性对所有存储在元素里的内容提供了访问管道
通过innerHTML访问元素内存储的内容:
<div id="div1">
<p id="story"> you are standing</p>
<strong>alone</strong> in the woods.
</div>
</body>
document.getElementById("story").innerHTML;
返回的内容是: you are standing alone in the woods.
innerHTML获取的是指定元素下的所有内容与标签
innerHTML也能用于设置网页内容
document.getElementById("story").innerHTML="You are <strong>not</strong> alone!";
innerHTML只用来设置可以包含文本的标签
Copy after login

That’s all the knowledge about controlling web pages with JavaScript - obtaining web page elements. I hope it will be helpful to you!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template