如何用javascript选择元素的所有子元素并更改CSS属性? [英] How to select all children of an element with javascript and change CSS property?

查看:128
本文介绍了如何用javascript选择元素的所有子元素并更改CSS属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个有32个孩子的div的项目。我需要创建一个下拉菜单,它将改变每个div和父级的背景。对于没有孩子的项目的其他部分,我一直在使用以下代码:

I am working on a project that has a div with 32 children. I need to create a dropdown menu that will change the background of each div and the parent. For the other parts of the project that don't have children, I have been using the following code:

function changediv(color) {
document.getElementById('div1').style.background = color;
}

HTML:

<select>
<option onClick="changediv('#555');">Hex</option>
<option onClick="changediv('blue');">Colorname</option>
<option onClick="changediv('url(example.com/example.png)');">Image</option>
</select>

我可以为每个孩子添加不同的ID(id1,id2,id3,...) ,但有32个孩子,我不仅需要添加32个ID,还需要32行Javascript。一定有更好的方法;以某种方式选择孩子甚至更改选择孩子的实际CSS代码。

I could just add a different ID to each child (id1,id2,id3,...), but there are 32 children and not only would I have to add 32 IDs, but also 32 lines of Javascript. There has to be a better way; somehow selecting children or even changing the actual CSS code that selects the children.

谢谢,Ian

推荐答案

虽然这可以用JQuery在一行中完成,但我假设您没有使用JQuery - 在这种情况下,您的代码将是:

While this can be done in one line with JQuery, I am assuming you are not using JQuery - in which case, your code will be:

var nodes = document.getElementById('ID_of_parent').childNodes;
for(var i=0; i<nodes.length; i++) {
    if (nodes[i].nodeName.toLowerCase() == 'div') {
         nodes[i].style.background = color;
     }
}

参见 http://jsfiddle.net/SxPxN/ 我创建的一个快速示例 - 点击更改'em以查看它的实际效果

See http://jsfiddle.net/SxPxN/ for a quick example I created - Click on "change 'em" to see it in action

这篇关于如何用javascript选择元素的所有子元素并更改CSS属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆