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';
EDIT:
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';
}
It still works everywhere but IE8. How can I change the above conditional for IE8?
EDIT 2:
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';
}
You need to use previousElementSibling
to get the previous Element node.
document.getElementById('p2').previousElementSibling.className = 'red';
http://jsfiddle.net/b6Bh8/
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.
I believe this would be the simplest way:
var p=document.getElementById('p2');
do {
p=p.previousSibling;
}while(p && p.tagName!='P');
p.className='red';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With