previousSibling不工作

dzu*_*011 6 javascript

我想<p>通过选择第二个<p>并使用previousSibling属性来定位div中的第一个但是它不起作用.

<div id="par">
<p id="p1">test</p>
<p id="p2">test</p>
</div>


document.getElementById('p2').previousSibling.className = 'red';
Run Code Online (Sandbox Code Playgroud)

编辑:

好吧它适用于除IE8之外的所有浏览器,但我希望它也可以在IE8中工作,我尝试了以下条件,但没有效果:

var c = document.getElementById('p2').previousElementSibling.className = 'red';

if (c == undefined) {

    c = document.getElementById('p2').previousSibling.className = 'red';
}
Run Code Online (Sandbox Code Playgroud)

它仍然适用于IE8.如何更改IE8的上述条件?

编辑2:

管理以使其在IE8中工作:

var c = document.getElementById('p2');

if (c.previousElementSibling) {

    c.previousElementSibling.className = 'red';

} else {

    c.previousSibling.className = 'red';

}
Run Code Online (Sandbox Code Playgroud)

Dog*_*ert 6

您需要使用它previousElementSibling来获取前一个Element节点.

document.getElementById('p2').previousElementSibling.className = 'red';
Run Code Online (Sandbox Code Playgroud)

http://jsfiddle.net/b6Bh8/

注意:根据上面的MDN链接,这不适用于IE <= 8.您可能需要循环previousSibling直到找到Element节点.