-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.

0

1 Answer 1

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>

Sign up to request clarification or add additional context in comments.

3 Comments

There is an alias for that .first() api.jquery.com/first
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 :)
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.