Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

previousSibling not working

Tags:

javascript

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';

}
like image 228
dzumla011 Avatar asked May 19 '13 10:05

dzumla011


2 Answers

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.

like image 126
Dogbert Avatar answered Nov 03 '22 00:11

Dogbert


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';
like image 45
anomaaly Avatar answered Nov 03 '22 02:11

anomaaly