js如何获取某id的子标签

思路:根据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、前后对比效果如下

原文地址:https://www.cnblogs.com/hhls/p/5616279.html