babcia.nazgul
babcia.nazgul

Reputation: 11

Is there any way to select elements in loop

I have a drop down menu created from li elements and each of them has a unique id. Instead of writing 4 different variables I want to create one loop (if possible and has sense) but I'm encountering a problem. After clicking on the particular li, the program should change the innerhtml with this li value.

function calories_calculator() {
  const list = new Array(3);
  list[0] = "1";
  list[1] = "2"; /////// those numbers are id of li elements
  list[2] = "3";
  list[3] = "4";
  const array = [];

  for (var i = 0; i < list.length; i++) {
    const f = document.getElementById(list[i]).onclick;
    if (true) {
      document.getElementById("display").innerHTML = list[i];
    }
  }
}

Upvotes: 0

Views: 84

Answers (2)

Dilshan
Dilshan

Reputation: 3001

Is this what you want?

  <ul>
    <li id="id1"><button>aaaaa</button></li>
    <li id="id2"><button>bbbbb</button></li>
    <li id="id3"><button>ccccc</button></li>
    <li id="id4"><button>ddddd</button></li>
  </ul>
  <div></div>
</body>
<script>
	const elements = document.querySelectorAll('li')
	elements.forEach(element => {
		element.addEventListener('click' , () => {
			document.querySelector('div').innerHTML = element.textContent;
		})
	})
</script>
</html>

Upvotes: 1

Catherine Luse
Catherine Luse

Reputation: 145

It looks like there is a syntax issue with your "onclick" event handler. The onclick should be followed by an equal sign and then the function. I found this answer which might be useful: Handling "onclick" event with pure JavaScript

Upvotes: 0

Related Questions