jake jake - 2 months ago 11x
Javascript Question

How can I select nextElementSibling item in loop one by one by every click after selecting on any random div in pure javascript?

I can select any item in the list by clicking on it and apply border. Then When I click on right arrow button to select next item from where I already picked item by clicking on it is not working. It selects next item but only once. I want that to apply for every item by clicking on right arrow one by one. same thing in reverse order for leftarrow. Can someone help me with pure javascript. below is my script working only for once clicked.

<ul id="gallery">
<li><img src="images/one.jpg" /></li>
<li><img src="images/two.jpg" /></li>
<li><img src="images/three.jpg" /></li>
<li><img src="images/four.jpg" /></li>

<div id="leftArw"></div>
<div id="rightArw"></div>

var list = document.getElementById("gallery").getElementsByTagName("LI");
var items, currentDiv, leftArw, rightArw;
leftArw = document.getElementById("leftArw"),
rightArw = document.getElementById("rightArw");
rightArw.addEventListener("click", right, false);

for (items = 0; items < list.length; items++) {
list[items].style.border = "none";
//list[items].addEventListener("click", currentItem, false);
list[items].onclick = function () {
currentDiv = this;
this.style.border = "5px solid red";

function right() {
currentDiv.nextElementSibling.style.border = "5px solid red";


// click handler to set the current "selected" element
document.querySelector("#gallery").addEventListener("click", function(e) {
  var currentlySelectedElement = e.currentTarget // the <ul> element

  if (currentlySelectedElement !== null) {
    currentlySelectedElement.className = "";

  e.target // the <li> element
   .className = "selected";
}, false);

// click handler for the "arrow" button
var right = (function() { // Closure to only query the DOM for the <li> elements once
  var items = document.querySelectorAll("#gallery li");

  function getSelectedItem() {
    var l = items.length,
        i = 0;

    for (; i < l; i++) {
      if (items[i].className === "selected") {
        return items[i];

    return null;

  // actual click handler to select the next element
  return function() {
    var selectedItem = getSelectedItem(),

    if (selectedItem !== null) {
      nextItem = selectedItem.nextElementSibling || items[0];

      selectedItem.className = "";
      nextItem.className = "selected";

document.querySelector("#rightArw").addEventListener("click", right, false);
.selected {
  outline: solid 1px red
#rightArw {
  width: 50px;
  height: 50px;
  background-color: yellow
<ul id="gallery">

<div id="rightArw"></div>