Reputation: 7724
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?
Upvotes: 1
Views: 1279
Reputation: 2333
You cant use nth-child
like that. Jquery have each
method which will allow you to easy iterate through all li
elements.
$('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>
Upvotes: 1
Reputation: 122027
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>
Upvotes: 2