试试这个:(只有子元素,而不是所有嵌套元素)
var pDiv = document.getElementById('parentDiv');
var cDiv = pDiv.children;
for (var i = 0; i < cDiv.length; i++) {
if (cDiv[i].tagName == "DIV") { //or use toUpperCase()
cDiv[i].style.color = 'red'; //do styling here
}
}
工作小提琴
不是最好的,但您可以参考以下内容:(只是为了获得更多知识)
Node.prototype.childrens = function(cName,prop,val){
//var nodeList = [];
var cDiv = this.children;
for (var i = 0; i < cDiv.length; i++) {
var div = cDiv[i];
if (div.tagName == cName.toUpperCase()) {
div.style[prop] = val;
//nodeList.push(div);
}
}
// return nodeList;
}
var pDiv = document.getElementById('parentDiv');
pDiv.childrens('div','color','red');