日期:2014-05-16  浏览次数:20440 次

JS 如何获取div的兄弟div
HTML code
<div>


------解决方案--------------------
HTML code
<div>1</div><div id='d'>2</div><div>3</div>
<script>
var div = document.getElementById('d');
var p = div.previousSibling;//前一个兄弟
var n = div.nextSibling; //后一个兄弟
</script>

------解决方案--------------------
JScript code
document.getElementById("divID").previousSibling//获取前一个兄弟节点
document.getElementById("divID").nextSibling//获取下一个兄弟节点

------解决方案--------------------
HTML code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head>

<body>
<div>
    <div>111</div>
    <div>222</div>
    <div id="demo">333</div>
    <div>444</div>
    <div>555</div>
</div>
<script type="text/javascript">
var obj = document.getElementById('demo'), ar = [];
var prevS = obj.previousSibling;
while(prevS != null) {
    if (prevS.nodeType == 1 && prevS.tagName == 'DIV') ar.push(prevS);
    prevS = prevS.previousSibling; 
}
var nextS = obj.nextSibling;
while(nextS != null) {
    if (nextS.nodeType == 1 && nextS.tagName == 'DIV') ar.push(nextS);
    nextS = nextS.nextSibling; 
}
for (var i = 0; i < ar.length; i ++) alert(ar[i].innerHTML);
</script>
</body>
</html>

------解决方案--------------------
探讨

HTML code
<div>1</div><div id='d'>2</div><div>3</div>
<script>
var div = document.getElementById('d');
var p = div.previousSibling;//前一个兄弟
var n = div.nextSibling; //后一个兄弟
</script>


用jquery的话比较方……

------解决方案--------------------
previousSibling这些在非IE的浏览器会取到空白节点啊貌似...囧~~
------解决方案--------------------
jquery的
HTML code

<!DOCTYPE HTML>
<html>
    <head>
        <meta charset="gb2312" />
        <title></title>    
        <script src="http://code.jquery.com/jquery-latest.js"></script>
    </head>
    <body>
        <div>1</div>
        <div>2</div>
        <div id="test">获取该节点之前的兄弟div</div>
        <div>4</div>
        <div>5</div>
        <script>
            $('#test').prevAll('div').each(function(){
                alert( this.innerHTML )
            })
        </script>
    </body>
</html>