How to get the prior elements of the specified one (previous sibling) in JavaScript

1 Answer

0 votes
<p>p p p</p>
<div id="div-1">div-1</div>
<div id="div-2">div-2</div>
<div id="div-3">div-3</div>
<script type="text/JavaScript">   
           
var el = document.getElementById('div-3').previousElementSibling;
console.log('Previous Siblings of div-3');
while (el) 
{
    console.log(el.nodeName + '<br />');
    el = el.previousElementSibling;
}

/*
run:

Previous Siblings of div-3
2 DIV<br />
P<br />

*/

</script>

 



answered May 28, 2016 by avibootz
...