previous兄弟不工作 [英] previousSibling not working
问题描述
我想通过选择第二个< p>
并使用 previousSibling
属性来定位div中的第一个< p>
,但是它不起作用.
I want to target the first <p>
inside the div by selecting the second <p>
and using previousSibling
property but it is not working.
<div id="par">
<p id="p1">test</p>
<p id="p2">test</p>
</div>
document.getElementById('p2').previousSibling.className = 'red';
好的,它可以在除IE8之外的所有浏览器上运行,但我也希望它也可以在IE8中运行,我尝试了以下条件,但没有任何作用:
OK it works on all browsers except IE8 but I want it to work in IE8 as well, I tried the following conditional but to no effect:
var c = document.getElementById('p2').previousElementSibling.className = 'red';
if (c == undefined) {
c = document.getElementById('p2').previousSibling.className = 'red';
}
除了IE8之外,它仍然可以在任何地方使用.如何更改IE8的上述条件?
It still works everywhere but IE8. How can I change the above conditional for IE8?
设法使它也可以在IE8中工作:
Managed to get it to work in IE8 as well:
var c = document.getElementById('p2');
if (c.previousElementSibling) {
c.previousElementSibling.className = 'red';
} else {
c.previousSibling.className = 'red';
}
推荐答案
您需要使用 previousElementSibling
获取上一个Element节点.
You need to use previousElementSibling
to get the previous Element node.
document.getElementById('p2').previousElementSibling.className = 'red';
注意:根据上面的MDN链接,这在IE< = 8上不起作用.您可能需要遍历 previousSibling
,直到找到一个Element节点.
Note: This does not work on IE <= 8 according to MDN link above. You would probably need to loop through previousSibling
until you find an Element node.
这篇关于previous兄弟不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!