思路:根據id獲取父對象,然后使用childNodes獲取所有子對象數組,關鍵代碼:
document.getElementById(div_id).childNodes; // 子對象數組
實例演示:點擊按鈕將為id為test的div標簽的所有子標簽添加red類,即字體顯示為紅色
1、HTML結構
<div id = "test">
<a href="#">我是超鏈接</a>
<input type="text" value="我是文本框">
<div>我是子div</div>
</div>
<input type='button' value='設置子元素樣式' onclick="fun()"/>
2、css樣式
.red{color:red !important;}
3、javascript代碼
function fun(){
objs = document.getElementById("test").childNodes;
for(k in objs)
objs[k].className = "red";
}
4、前后對比效果如下


