Dan Dan - 3 months ago 7
HTML Question

Iterating through li elements

I have a structure in my

HTML
code which looks a little like this.

<nav id="nav">
<ul>
<li>Li 1</li>
<li>Li 2</li>
<li>Li 3</li>
</ul>
</nav>


To iterate through the list I am using
JavaScript
and the
jQuery
plugin. The code looks a little like this.

for(i = 1; i <= navSide.children("ul").children("li").length; i++) {
console.log(navSide.children("ul").children("li:nth-child(i)").offset().top);
}


However, the problem with doing it this way is that I get an
Uncaught Error: Syntax error, unrecognized expression: :nth-child
. What is the correct, most efficient, way to do what I am trying to do?

Answer

You can use each() loop

$('#nav li').each(function() {
  console.log($(this).offset().top);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav id="nav">
  <ul>
    <li>Li 1</li>
    <li>Li 2</li>
    <li>Li 3</li>
  </ul>
</nav>

Comments