-2

How can I combine a jQuery variable with a pseudo class - for example:

listItem = $('li');

listItem.addClass();      // Works on all li's
$(listItem).addClass();   // Works on all li's

$('li:first-child').addClass(); // Works ( on first li )

$(listItem + ':first-child').addClass(); // Doesn't Work..

Similarly I'd like to be able to do this with data attributes, for example to use some variant of:

listItem[data-index="1"]

instead of:

    $('li[data-index="1"]')

I've found a couple questions which deal with variables after such as $('#element-' + variable'), which don't help in this case.

jQuery: using a variable as a selector,

jQuery selectors with variables

And also tried 'template literals' ( ${id} ) to no avail.

Toki
  • 517
  • 3
  • 9
  • 27

1 Answers1

0

I would suggest using the .children(), like so:

listItem.children().eq(0).addClass();

But you are not trying to select the child elements, you want to first element in the Group.

listItem.eq(0).addClass();

That should work as you expect.

$(function() {
  var listItems = $("li");
  listItems.eq(0).addClass("first");
});
.first {
  background-color: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul>
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
  <li>Item 4</li>
  <li>Item 5</li>
</ul>
Twisty
  • 30,304
  • 2
  • 26
  • 45
  • There is an alias for that `.first()` https://api.jquery.com/first/ – Yury Tarabanko Mar 12 '21 at 16:13
  • Thanks both for contributing - I was hoping there was a more direct way of doing it but I guess that answers my question in that these approaches are required - no real bother at the end of the day :) – Toki Mar 12 '21 at 16:17
  • @CultDigital I hope it helps. If it does, I hope you will upvote the answer. If it does answer your question, I hope you will mark it as the answer. – Twisty Mar 12 '21 at 16:54