Reputation: 7153
What's the correct syntax when you want to call the nth-child
of an element that's a variable and when the index is also a variable.
let i = 7;
let listItem = $('#somelist li');
listItem: nth - child(i).css('display', 'none'); // nope
$(`${pageNavLi}:nth-child(${i})`).css('display', 'none'); // nope
I've tried a bunch of template strings and can't seem to land it.
Upvotes: 1
Views: 31
Reputation: 899
you can use eq()
to specific child
Description: Select the element at index n within the matched set.
with these
listItem.eq(i)
OR
listItem.filter(':eq(' + i + ')')
how to use?
let i = 3;
let listItem = $('#somelist li');
listItem.eq(i).css('display', 'none');
console.log(listItem.eq(i).text())
//OR
listItem.filter(':eq(' + i + ')').css('display', 'none');
console.log(listItem.filter(':eq(' + i + ')').text())
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="somelist">
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
<li>Bubble Milk Tea</li>
</ul>
Upvotes: 0
Reputation: 21672
If you're trying to hide an element by index, you can use jQuery .eq()
:
let i = 1;
let listItem = $('li');
listItem.eq(i).hide()
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
Upvotes: 0
Reputation: 10227
You can use the get(n)
and supply it with the index. More info
let i = 1;
let listItem = $('li');
console.log(listItem.get(i));
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<ul>
<li>Coffee</li>
<li>Tea</li>
<li>Milk</li>
</ul>
Upvotes: 2