<ul>
<li class="slonik">1</li>
<li class="begemotik">2</li>
<li class="begemotik">3</li>
<li class="begemotik">4</li>
<li class="slonik">5</li>
<li class="slonik">6</li>
<li class="slonik">7</li>
<li class="begemotik">8</li>
<li class="begemotik">9</li>
</ul>
<script>
var li = document.querySelectorAll('li');
li.forEach(el=>el.onclick=e=>{
var cls = el.className, th = el;
while (el = el.previousElementSibling) {
if (el.className !== cls) break;
else el.style.color = 'red';
}
while (th = th.nextElementSibling) {
if (th.className !== cls) break;
else th.style.color = 'red';
}
});
</script>