0

Say I have an array of HTML elements that looks like this...

var info = [<tr>...</tr>, <tr class="name">...</tr>, <tr class="colour">...</tr>]

If I only want to select the class name from the array info, how can I do this with jQuery? I expected something like the following to work:

$([info, '.name:first']);

But it didn't. Am I getting some minor detail wrong here or can you simply not select from arrays with jQuery?

2
  • $(info).filter(".name:first")? Commented Apr 17, 2016 at 16:11
  • Hmm, doesn't seem to work in Chrome's Dev Tools Commented Apr 17, 2016 at 16:12

2 Answers 2

2

You can use the second argument of jQuery:

var filtered = $('.name:first', info);

This is equivalent to:

var filtered = $(info).find('.name:first');

If the selector needs to find top level elements, as stored in the array, then use filter:

var filtered = $(info).filter('.name:first')
Sign up to request clarification or add additional context in comments.

1 Comment

This is what I was looking for. Brilliant! Thank you very much.
0

Assuming that the contents of the Array are genuine element nodes, then it would be easier to simply use Array.prototype.filter() and Element.matches():

var items = Array.from(document.querySelectorAll('tr')),
    test = items.filter(row => row.matches('tr.test'));
console.log(test);
<table>
  <tbody>
    <tr class="colour"></tr>
    <tr class="colour"></tr>
    <tr class="colour"></tr>
    <tr class="test"></tr>
  </tbody>
</table>

The above snippet uses the (new-ish) Arrow function syntax, which is equivalent to the following:

var items = Array.from(document.querySelectorAll('tr')),
    test = items.filter(function(row){
      return row.matches('tr.test');
    });
console.log(test);
<table>
  <tbody>
    <tr class="colour"></tr>
    <tr class="colour"></tr>
    <tr class="colour"></tr>
    <tr class="test"></tr>
  </tbody>
</table>

Element.matches() tests the element (Element) against a supplied CSS selector and, if that supplied selector would match the Element, returns a Boolean true, otherwise false.

Array.from() converts the results of the Array-like collection returned from document.querySelectorAll() into an Array, in order to use Array methods, such as Array.prototype.filter(), which retains those elements in the Array for which the supplied assessment returns true/truthy values.

References:

Comments

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.