通过javascript获取比当前元素低1级的元素 [英] Get elements just 1 level below the current element by javascript

查看:64
本文介绍了通过javascript获取比当前元素低1级的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要访问DOM树并获取当前元素下方1级的元素。

I need to access the DOM tree and get the elements just 1 level below the current element.

阅读以下代码:

<div id="node">
    <div id="a">
        <div id="aa">
            <div id="ab">
                <div id="aba"></div>
            </div>
        </div>
    </div>
    <div id="b">
        <div id="ba">
            <div id="bb">
                <div id="bba"></div>
            </div>
        </div>
    </div>
    <div id="c">
        <div id="ca">
            <div id="cb">
                <div id="cba"></div>
            </div>
        </div>
    </div>
</div>

我想在节点下获得3个元素a,b,c 。我该怎么办?

I want to get the 3 elements "a", "b", "c" under "node". What should I do?

var nodes = node.getElementsByTagName(div)< ----我得到所有的div但不是我需要的3个div。

var nodes = node.getElementsByTagName("div") <---- I get all the divs but not the 3 divs I need.

var nodes = node.childNodes; < ----在IE中工作,但FF包含文本节点

var nodes = node.childNodes; <---- works in IE, but FF contains Text Node

有谁知道如何解决问题?

Does anyone know how to solve the problem?

推荐答案

您可以使用排除所有非元素节点的函数:

You could use a function that rules out all non-element nodes:

function getChildNodes(node) {
    var children = new Array();
    for(var child in node.childNodes) {
        if(node.childNodes[child].nodeType == 1) {
            children.push(child);
        }
    }
    return children;
}

这篇关于通过javascript获取比当前元素低1级的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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