白龙网认为,使用JavaScripit修改、打印元素的内容、属性、样式时,首先要要在文档中找到元素,然后调用相关的属性、方法去实现。
例如,要访问某标签的子元素,可以使用children属性、querySelector()、querySelectorall()方法来实现。如果访问某标签内的一个子元素,则可以使用children[i],或者指定选择器时调用querySelectorall()[i]来实现。具体操作,来看一看下面两个案例。
一、通过属性访问子元素
二、使用方法遍历子元素
一、通过属性访问子元素
<div id="demo">
<h1>大标题</h1>
<h2>副标题</h2>
<p>段落说明性文件</p>
<em>开始文字要倾斜一下</em>
<a href="www.bailong.org.cn">百度链接</a>
<a href="www.bailong.org.cn">新浪链接</a>
</div>
子元素个数为:<small id="total"></small><br />
获取第二个元素的文本信息:<big id="demo2"></big><br />
打印每个子元素的下标:<em id="xiabiao"></em><br />
第六个子元素的网址是:<b id="demo3"></b><br />
输出元素的样式:<cite id="colors"></cite>
<script>
myFunction();
function myFunction(){
//定义子元素的数量
var total = document.getElementById('demo').children.length;
//打印子元素的总数
document.getElementById('total').innerHTML = total;
//定义子元素的集合
var showElement = document.getElementById('demo').children;
//修改第一个子元素的内容
showElement[0].innerHTML = "这是一个大标题";
//修改第一个子元素的背景颜色
showElement[0].style.backgroundColor = 'yellow';
//打印第二个子元素的内容
document.getElementById('demo2').innerHTML = showElement[1].textContent;
//打印所有子元素的背景颜色为红色
for(i=0;i<total;i++){
showElement[i].style.backgroundColor = 'red';
}
//隐藏第二个子元素的内容
showElement[1].style.display = 'none';
//设置第三个子元素的大小为50PX
showElement[2].style.fontSize = '50px';
//设置第四个子元素为粗体
showElement[3].style.fontWeight = '900'
//修改第五个子元素的网址为www.baidu222.com
showElement[4].href = 'www.bailong.org.cn';
//打印第六个子元素的网址
document.getElementById('demo3').innerHTML = showElement[5].href;
document.getElementById('colors').innerHTML = showElement[0].style.backgroundColor;
}
</script>
二、使用方法遍历子元素
<div id="second"> <h1>标题</h1> <h2>副标题</h2> <a href="www.bailong.org.cn">百度</a> <a href="www.bailong.org.cn" target="_blank">新浪</a> <a href="www.bailong.org.cn" title="提示信息 ">搜狐</a> </div> <p id="cs"></p> <script> secondFunction(); function secondFunction(){ //给指定选择器H1的内容修改为Title document.querySelector('#second h1').innerHTML = "Title"; //给指定选择器H2的内容修改为fu Title document.querySelector('#second h2').innerHTML = "fu Title"; //给指定选择器a添加颜色为红色 document.querySelector('#second a').style.color = 'red'; //给DIV标签内第3个a元素添加颜色为绿色 document.querySelectorAll('#second a')[2].style.color = 'green'; //给属性为target的a标签添加一个边框 document.querySelector('a[target]').style.border = "2px solid red"; //给属性为title的a标签添加一个边框 document.querySelector('a[title]').style.backgroundColor = "brown"; } </script>