Home > Article > Web Front-end > JavaScript controls the web page-getting web page elements_javascript skills
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的值
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标签
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只用来设置可以包含文本的标签
That’s all the knowledge about controlling web pages with JavaScript - obtaining web page elements. I hope it will be helpful to you!